How to insert lines with numbers from X to Y into another file after line Z

awksedtext processing

I created two files:

echo -e "1\n2\n3\n4\n5" > 123.txt
echo -e "a\nb\nc\nd\ne" > abc.txt

I want to get the file 123.txt with the following contents:

1
2
3
b
c
d
4
5

So in other words insert the rows with numbers from 2 to 4 of the file abc.txt into the file 123.txt after the third line.

I have reviewed the many similar questions here, but did not find a suitable answer. Nevertheless I got the lines:

sed -n '2,4p' abc.txt

and put some text into the file after the third line:

sed -i '3a\mytext' 123.txt

How to do this using the previous command stdout or/and a sed/awk single command?

Best Answer

If your system has the GNU version of sed, you can use the GNU extension r command:

r filename
    As a GNU extension, this command accepts two addresses.

    Queue the contents of filename to be read and inserted into the
    output stream at the end of the current cycle, or when the next input 
    line is read. Note that if filename cannot be read, it is treated as 
    if it were an empty file, without any error indication.

    As a GNU sed extension, the special value /dev/stdin is supported for 
    the file name, which reads the contents of the standard input. 

For example,

$ sed '3r /dev/stdin' 123.txt < <(sed -n '2,4p' abc.txt)
1
2
3
b
c
d
4
5
Related Question