I know sed
can append text in a few different ways:
to append the string NEW_TEXT
:
sed -i '/PATTERN/ a NEW_TEXT' file
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?
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.
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>/
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]$
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.
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
You can use redirection operator with r
command:
sed -i '/ZZZ/r '<(sed -n '1p' file1) file2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With