CLI tip 24: inserting file contents one line at a time
The R
command provided by GNU sed
is very similar to r
with respect to most of the rules seen in an earlier tip. But instead of reading entire file contents, R
will read one line at a time from the source file when the given address matches. If entire file has already been read and another address matches, sed
will proceed as if the line was empty.
Here's an example:
$ cat ip.txt
* sky
* apple
$ cat fav_colors.txt
deep red
yellow
reddish
brown
# add a line from 'ip.txt'
# whenever a line from 'fav_colors.txt' contains 'red'
$ sed '/red/R ip.txt' fav_colors.txt
deep red
* sky
yellow
reddish
* apple
brown
You can combine with other sed
commands to solve various kind of problems. For example, to replace the matching lines:
# empty // will refer to the previously used regex, /red/ in this case
$ sed -e '/red/R ip.txt' -e '//d' fav_colors.txt
* sky
yellow
* apple
brown
And, here's how you can interleave contents of two files:
# /dev/stdin will get data from stdin (output of 'seq 4' here)
# same as: seq 4 | paste -d'\n' fav_colors.txt -
$ seq 4 | sed 'R /dev/stdin' fav_colors.txt
deep red
1
yellow
2
reddish
3
brown
4
# using 'paste' here will add a newline when stdin runs out of data
$ seq 2 | sed 'R /dev/stdin' fav_colors.txt
deep red
1
yellow
2
reddish
brown
Video demo:
See also my CLI text processing with GNU sed ebook.