Skip to main content
added 46 characters in body
Source Link
Sundeep
  • 12.2k
  • 3
  • 28
  • 75

With GNU sed, similar to awk+getline

$ perlsed -pee 'BEGIN'/^!!/{ chomp(@a=`catR file2.txt`)txt' }-e s/^!!.*/$a[$i++]/e''d}' file1.txt 
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • @a array stores all the lines from file2.txt with ending newline character chopped off. BEGINR block to execute thiswould give a line of code onceone at start of scripta time
  • order is important, first s/^!!.*/$a[$i++]/eR substitute lines starting withand then !!d

With `perl`
$ < file2.txt perl -pe '$_ = <STDIN> if /^!!/' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • pass the file with value fromreplacing lines as standard input, so that we can read it using @a<STDIN> array. Indexfilehandle
  • if matching line is saved in $i variable (default value zero) and gets incremented for every access. Thefound, replace e$_ flag enables use of code instead of string in replacement sectionwith a line from standard input
$ perl -pe 'BEGIN{ chomp(@a=`cat file2.txt`) } s/^!!.*/$a[$i++]/e' file1.txt 
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • @a array stores all the lines from file2.txt with ending newline character chopped off. BEGIN block to execute this line of code once at start of script
  • s/^!!.*/$a[$i++]/e substitute lines starting with !! with value from @a array. Index is saved in $i variable (default value zero) and gets incremented for every access. The e flag enables use of code instead of string in replacement section

With GNU sed, similar to awk+getline

$ sed -e '/^!!/{R file2.txt' -e 'd}' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • R would give a line one at a time
  • order is important, first R and then d

With `perl`
$ < file2.txt perl -pe '$_ = <STDIN> if /^!!/' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • pass the file with replacing lines as standard input, so that we can read it using <STDIN> filehandle
  • if matching line is found, replace $_ with a line from standard input
Source Link
Sundeep
  • 12.2k
  • 3
  • 28
  • 75

$ perl -pe 'BEGIN{ chomp(@a=`cat file2.txt`) } s/^!!.*/$a[$i++]/e' file1.txt 
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
  • @a array stores all the lines from file2.txt with ending newline character chopped off. BEGIN block to execute this line of code once at start of script
  • s/^!!.*/$a[$i++]/e substitute lines starting with !! with value from @a array. Index is saved in $i variable (default value zero) and gets incremented for every access. The e flag enables use of code instead of string in replacement section