how can sed get patterns from a file

4

2

I have two files one holds a list of patterns, another need to be changed based on these patterns. So far I have been experimenting with

cat patterns.txt| xargs -n1| sed 's/patternfromfile/subtitution/'

but I am not sure how to enter xargs into 's/here//'

Thank you

sgp667

Posted 2014-02-19T20:02:58.807

Reputation: 563

Answers

5

You may want the -i option to xargs (check the man page for details). That essentially replaces {} with the pattern, and runs the command once per pattern. So, it'll run sed on the file once per pattern; you'll need to bear that in mind when creating your patterns.

user@host [/tmp]$ cat patterns
a
[pd]ie
user@host [/tmp]$ cat file
hat
cherry pie
die alone
eat cake
user@host [/tmp]$ cat patterns | xargs -i sed 's/{}/moo/' file
hmoot
cherry pie
die moolone
emoot cake
hat
cherry moo
moo alone
eat cake

Alternatively, you could use something else to dynamically build the sed script from your patterns file. For example, you could use sed on your pattern file to apply them all in one pass over the file. :)

user@host [/tmp]$ sed 's|^|s/|;s|$|/moo/;|' patterns | tee patterns.sed
s/a/moo/;
s/[pd]ie/moo/;
user@host [/tmp]$ sed -f patterns.sed file
hmoot
cherry moo
moo moolone
emoot cake

dannysauer

Posted 2014-02-19T20:02:58.807

Reputation: 837

Thats it! It worked perfectly thank you so much. – sgp667 – 2014-02-24T16:57:50.257

0

Without knowing what patterns you have:

Use -i option if you want to edit yourfile directly:

   while read pattern
    do
        sed -i 's/"${pattern}"/substitution/' yourfile
    done < patterns.txt

Alternatively redirect output to a new file:

   while read pattern
    do
        sed 's/"${pattern}"/substitution/' yourfile >> outfile
    done < patterns.txt

suspectus

Posted 2014-02-19T20:02:58.807

Reputation: 3 957

close: the variable substitution will not occur due to the single quotes. – glenn jackman – 2014-02-19T20:56:45.480

0

You can build a regex like this:

regex=$(tr '\n' '|' < patterns.txt)
sed -ri "s/$regex/replacement/" filename

You may choose to add the "g" flag to the s/// command.

glenn jackman

Posted 2014-02-19T20:02:58.807

Reputation: 18 546