Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed append text obtained from stdout

Tags:

bash

sed

I know sed can append text in a few different ways:

  1. to append the string NEW_TEXT:

    sed -i '/PATTERN/ a NEW_TEXT' file
    
  2. to append contents of file file_with_new_text:

    sed -i '/PATTERN/ r file_with_new_text' file
    

However, is there anyway to append text piped to sed via stdout? I am hoping to obtain the equivalent of:

# 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 having to use a temporary file. Is this possible?

like image 879
jayflo Avatar asked Feb 07 '14 21:02

jayflo


People also ask

Does SED -I modify an empty file?

The syntactically correct sed -i '' 'a$\ (newline) some text' somefile.txt does not actually modify an empty file on MacOS Big Sur, like @doak already remarked (presumably regarding Linux). If you're just appending text to the end of the file then you wouldn't use sed in the first place.

How to add a font to a line in SED?

some command | sed -n '/\[Z\]$/ s/^/<font>/;/\[Z\]$/ s/$/<\/font>/p' It basically has two parts : /\[Z\]$/ s/^/<font>/will match the line that has [Z]at last, then will add <font>at the start of the line by s/^/<font>/

How do I read a file in SED?

But if you absolutely must do this in sed, you can use sed's r command to read a file. For example: [ghoti@pc ~/tmp]$ cat one RED BLUE [ghoti@pc ~/tmp]$ cat two green yellow [ghoti@pc ~/tmp]$ echo ">> start"; sed '$r two' one; echo ">> end" >> start RED BLUE green yellow >> end [ghoti@pc ~/tmp]$

How to add string before and after the matching pattern using SED?

Add string before and after the matching pattern using ‘\1’ The sequence of matching patterns of `sed` command is denoted by ‘\1’, ‘\2’ and so on. The following `sed` command will search the pattern, ‘Bash’ and if the pattern matches then it will be accessed by ‘\1′ in the part of replacing text.


2 Answers

You can read from /dev/stdin. Clearly, this will only work once per sed 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
like image 57
that other guy Avatar answered Sep 30 '22 04:09

that other guy


You can use redirection operator with r command:

sed -i '/ZZZ/r '<(sed -n '1p' file1) file2
like image 35
anubhava Avatar answered Sep 30 '22 04:09

anubhava