Matthew.J
Matthew.J

Reputation: 65

File content as regex for grep

I have file with "exp regex" lines. This file can contain lines with other text. For example:

exp [a-zA-Z].*\.sh~$
exp test
tmp too
exp tmp
trololo

I need to grep content of this file with egrep file '^exp ' | sed 's/^exp //' Result of this is:

[a-zA-Z].*\.sh~$
test
tmp

But I need this grep results separated by | instead of \n

[a-zA-Z].*\.sh~$|test|tmp

because I need use this result as another grep regex. For example to print files matched by nested grep:

ls | egrep "`egrep file '^exp ' | sed 's/^exp //'\`"

after nested grep | sed substitution

ls | egrep "[a-zA-Z].*\.sh~$|test|tmp"

Or is there better way to export regexs from file and use them for filter files?

Kent: how can I use this in subtitution? I thougth it is:

ls | egrep "`awk '/^exp /{sub(/^exp /,"");s=(s?s"|":s) sprintf("%s",$0)}END{print s}' file`"

but I am propably wrong.

Upvotes: 0

Views: 778

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185025

Try doing this :

grep '^exp ' file.txt | sed 's/^exp //' | paste -sd '|'

or even better, no need grep, sed cad do it natively :

sed -n '/^exp/s/^exp //p' file.txt | paste -sd '|'

Last but not least, if you are open to one-liners :

perl -ne 'push @arr, $1 if /^exp (.*)/;END{print join "|", @arr}' file.txt

Upvotes: 3

Kent
Kent

Reputation: 195039

you could save the grep and sed, and use single process: awk one-liner

awk '/^exp /{sub(/^exp /,"");s=(s?s"|":s) sprintf("%s",$0)}END{print s}' file

test a bit:

kent$  on feature at master!? echo "exp [a-zA-Z].*\.sh~$
exp test
tmp too
exp tmp
trololo"|awk '/^exp /{sub(/^exp /,"");s=(s?s"|":s) sprintf("%s",$0)}END{print s}'
[a-zA-Z].*\.sh~$|test|tmp

Upvotes: 2

Related Questions