Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

up vote 1 down vote accepted

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
share|improve this answer
    
Thats it! It worked perfectly thank you so much. –  sgp667 Feb 24 at 16:57

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
share|improve this answer
    
close: the variable substitution will not occur due to the single quotes. –  glenn jackman Feb 19 at 20:56

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.