简体   繁体   中英

How to use sed on macOS to replace a line with bash script

I am on macOS High Sierra, and I've had a few issues with sed, after spending a day on Google and this site, I've honestly tried everything I could think of and was suggested.

I have an example.txt file with 3 lines. line1 line2 line3

The 3 lines can be anything, I do not know them upfront. (scenario) And at some point I do know what the line is going to be.

All I wish to achieve is to use 'whatever' onliner that basically says: in that file, replace line 2, with the new data.

sed -i "2s/.*/$NEW_DATA/" "$FILENAME"

This should work, but on macOS, this does not.

sed -ie "2s/.*/$NEW_DATA/" "$FILENAME"

Note the e? Someone on here suggested to add an e, and yes, that works.. but it means it adds the e behind the .txt. I end up with 2 files, example.txt and example.txte

sed -i'' "2s/.*/$NEW_DATA/" "$FILENAME"

Note the '' behind -i, and yes, without a space? This should work too. It doesn't, it will complain that command c requires \\

I could go on, but the request is quite simple:

on macOS, in a bash shell script, how do I simply replace a specified line of text in a .txt file, with a completely new line of text -- not knowing what the line of text was before?

If this can be a simple macOS one liner with awk or whatever, that's fine. It doesn't have to be sed. But when I search this site, it seems to be the recommended one to go with in this regards.

From the sed man page in macOS:

-i extension
         Edit files in-place, saving backups with the specified extension. 
         If a zero-length extension is given, no backup will be saved. 

Therefore this can be used to replace line 2 without keeping backup:

sed -i '' "2s/.*/$NEW_DATA/" testfile.txt

If the goal is just to replace contents of line 2 awk could also be used, for example:

awk 'NR==2{$0="your content"}1' testfile.txt > testfile.tmp && mv testfile.tmp testfile.txt

The -i argument with sed on MacOS requires a file extension for the backup file, example:

/usr/bin/sed  -i .bkp  "2s/.*/$NEW_DATA/" "$FILENAME"

If you don't want a backup file, use:

/usr/bin/sed  -i"" "2s/.*/$NEW_DATA/" "$FILENAME"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM