CLI tip 18: inserting file contents using GNU sed
The r
command accepts a filename as argument and when the address is satisfied, entire contents of the given file is added after the matching line. This is a robust way to add multiline text literally.
$ cat ip.txt * sky * apple $ cat fav_colors.txt deep red yellow reddish brown # space between r and filename is optional # adds entire contents of 'ip.txt' after each line containing 'red' $ sed '/red/r ip.txt' fav_colors.txt deep red * sky * apple yellow reddish * sky * apple brown
The e
flag is the easiest way to insert file contents before the matching lines. Similar to the r
command, the output of an external command (cat
in the below example) is inserted literally.
$ sed '/red/e cat ip.txt' fav_colors.txt * sky * apple deep red yellow * sky * apple reddish brown
See Adding content from file chapter from my GNU sed ebook for many more examples, gotchas, details about the
R
command and so on.
Video demo:
See also my CLI text processing with GNU sed ebook.