What I would do is to append all the lines in a great line and replace the content.
$ cat f
import java.io.File;
import java.io.File;
$ sed -n 'N
${
s/import java.io.File;/import java.io.IOException/
p
}' f
import java.io.IOException
import java.io.File;
How it works: first, I suppress the line printing, which is the default behavior, passing the -n
option to sed.
Then there comes the sed commmands. The first one is the N
command: it appends a newline and the next line of the stream to the current one, maintaining then at the pattern space. This will change the current line to the next one, and then the next line will be appended... until the end of the file.
At the end of the file and after the N
command to be executed at the last line as well, the pattern space will contain all the lines. Then, at the end of the file (which is specified by the $
address) we just replace the desired line with:
s/import java.io.File;/import java.io.IOException/
Since the s///
command does only one replacement per iteration at the pattern space by default, it will only replace the first line. Now the pattern space has the line replaced, but will not be printed out since we used the -n
option. So, we need to print it with the p
command. Once we will execute two operations at the end of the file, we adress it with $
and put the operations between brackets ({}
).
There, we just presented the sed commands in more than one line for clarity. We can use them all in one line; just separate them by semicolons:
$ sed -n 'N;${s/import java.io.File;/import java.io.IOException/;p;}' f
import java.io.IOException
import java.io.File;
HTH