How do I replace ALL text in a file after a certain line with the content of another text file, using sed/awk?
In GNU/awk:
Name the two files as arguments.
awk '{ print; } /^### REPLACE EVERYTHING AFTER THIS LINE ###$/ { nextfile; }' fn1 fn2
Print all lines until "replace after" line is found, then read from other file & quit:
sed '/^### REPLACE EVERYTHING AFTER THIS LINE ###$/{r replacement_file.txt
q;}' original_file.txt
- use
sed -i
to save changes - or
... > tmp && mv tmp original
Using sed
:
sed -n -e '1,/^### REPLACE EVERYTHING AFTER THIS LINE ###$/{ p; d; }' \
-e 'r replacement_file.txt' \
-e 'q' original_file.txt
The three sed
blocks do this:
- The first block prints all lines from line 1 to the line with the special contents. I print these lines explicitly with
p
and then invoked
to force a new cycle to start ("print; next
" inawk
). - After the initial lines have been outputted by the first block, the second block outputs the contents of the extra file.
- The editing script is then terminated.
Ordinarily, q
in the third block would output the current line before quitting (this would be the line in the example data reading text_that_will
), but since sed
is invoked with -n
, this default outputting of a line at the end of a cycle is inhibited.
The result of the above command, given your data, is
common_text
### REPLACE EVERYTHING AFTER THIS LINE ###
testing123
this_is_the_replacement_text
To update the original file, you could use sed -i ...
, or redirect the output to a new file that you then replace the original with:
sed ... original_file.txt >original_file.txt.new &&
mv original_file.txt.new original_file.txt