Skip to content
Advertisement

Replace certain line in a text with a certain line in another text

Taking off from this question, I want to replace a certain line in one text file with another line from another text file. Example:

text1 contains:

line 1
line 2
line 3

text2:

line 4
line 5
line 6

I want to replace the 2nd line in text1 with the second line from text2, the solution in the above mentioned question works by adding all the content of text2 in place of the line to be changed, not a certain line against a certain line.

The actual problem I’m having is that I have two files, one contains a list of data that need to run through the same command in another file, I’m looking for a method of automation, a script that automatically replaces a certain string in the second file with the first line in the first file then replaces the same string with the second line and go on.. not sure how to do that but I thought if I could work out that sed command I could probably just make copies of it equal to the number of lines that I have and run them in sequence.

Advertisement

Answer

This might work for you (GNU sed):

sed -n '2p' file2 | sed -e '2r /dev/stdin' -e '2d' file1

Pipe the contents of the file2 into file1 i.e. print the second line of file2 to stdout. Replace the second line of file1 with the contents of stdin.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement