0

Right now I'm using

echo sed '/\Random/a \
 newly added line' info.txt

to append some text to a file but I also need to add text below a certain string let's say random, I know it is possible with sed, But when the script runs, it shows the new file content in the console, but it is not actually showing the same changes in the file.

example:-

Input File

Some text
Random
Some stuff

Output File

Some text
Random
newly added line
Some stuff

1 Answers1

2

I'm going to assume that echo is just a typo because unless there's something specific with your environment, that same command just gives the output

sed '/Random/a\
newly added line' info.txt

If you want sed to actually operate on the file instead of sending to stdout, then you need to use the -i switch as supported by a few sed implementations though with different syntax:

  • GNU, busybox, NetBSD, OpenBSD at least:

    sed -i '/Random/a\
    newly added line' info.txt 
    
  • FreeBSD, macos:

    sed -i '' '/Random/a\
    newly added line' info.txt 
    
  • The -i switch is not available in the Solaris sed.

It's a good idea to run it without -i at first in order to make sure that it's doing what you want. Once you're sure that it is, add -i and you'll have what you need.

The contents of the file will then be the following which can be confirmed with cat info.txt:

Some text
Random
newly added line
Some stuff
Kusalananda
  • 333,661
Nasir Riley
  • 11,422
  • 1
    What \R does in a sed regexp is unspecified, so that backslash could be harmful in sed implementations where \R has a special meaning. For instance, in perl REs, \R matches a linebreak. You could imagine future versions of GNU sed doing the same like they added support for perl's \s to match any whitespace character. (you're missing some quotes btw). – Stéphane Chazelas Sep 25 '22 at 13:03
  • @StéphaneChazelas Weird. I copied that line directly from my terminal where the quotes were there. I wasn't suggesting that it was bad to escape the R but just in this case, it isn't needed. In any event, I removed that from my answer as it doesn't hurt anything to have it there and it could be necessary in other cases such as what you've mentioned. – Nasir Riley Sep 25 '22 at 13:20