Sed add text retrieved from stdout

I know that I sedcan add text in several ways:

  • add line NEW_TEXT:

    sed -i '/PATTERN/ a NEW_TEXT' file
    
  • add file contents file_with_new_text:

    sed -i '/PATTERN/ r file_with_new_text' file
    

However, is there a way to add text passed through sedvia stdout? I hope to get the equivalent:

# XXX,YYY,ZZZ are line numbers
# The following appends lines XXX-YYY in file1
# after line ZZZ in file2.

sed 'XXX,YYY p' file1 > /tmp/file
sed -i 'ZZZ r /tmp/file' file2

without using a temporary file. Is it possible?

+4
source share
2 answers

You can read /dev/stdin. It is clear that this will only work once in a single process.

Example:

$ cat file1
this is text from file1
etc

$ cat file2
Hello world from file2

$ sed -n '1p' file1 | sed -i '$ r /dev/stdin' file2

$ cat file2
Hello world from file2
this is text from file1
+6
source

You can use the redirection operator with the command r:

sed -i '/ZZZ/r '<(sed -n '1p' file1) file2
+3
source

Source: https://habr.com/ru/post/1525866/


All Articles