Hari Sundararajan
Hari Sundararajan

Reputation: 678

sed - search in one file the contents of another

So there are other similar questions, but here's in particular what I want to do -

I have one really long file. long.txt that looks like

line1 
line2
line3
line4
line1
line1
line2
line8
line1
line2

now, I have another file, pattern.txt that looks like

line1
line2 

Finally, replace.txt that looks like

newline1
newline2 

Is there a way to call sed such that after running it on the above, I end up with

newline1 
newline2
line3
line4
line1
newline1
newline2
line8
newline1
newline2

Upvotes: 0

Views: 307

Answers (2)

potong
potong

Reputation: 58473

This might work for you (GNU sed):

cat <<\! >cat.sed
> :a;$!{N;ba};s/\n/\\n/ 
> !
sed ':a;$!'"{N;ba};s/$(sed -f cat.sed pattern.txt)/$(sed -f cat.sed replace.txt)/g" long.txt
newline1
newline2
line3
line4
line1
newline1
newline2
line8
newline1
newline2

Explanation:

  • Build the LHS (pattern) and RHS (replace) of a sed substitution using a generic sed script - cat.sed
  • Plug the above substitution into another sed script that processes the long.txt file.

Upvotes: 2

kev
kev

Reputation: 161844

$ paste -d'/' pattern.txt replace.txt | sed 's@.*@s/&/@' >script.sed
$ sed -f script.sed long.txt

Upvotes: 0

Related Questions