简体   繁体   English

如何在macOS上使用sed用bash脚本替换行

[英]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. 我在使用macOS High Sierra时,在sed上遇到了一些问题,在Google和该网站上呆了一天后,我已经尽力尝试了我能想到的一切,并提出了建议。

I have an example.txt file with 3 lines. 我有3行的example.txt文件。 line1 line2 line3 第1行第2行第3行

The 3 lines can be anything, I do not know them upfront. 3行可以是任何内容,我不预先知道它们。 (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. 我想要实现的只是使用基本上说的“无论如何”的onliner:在该文件中,用新数据替换第2行。

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

This should work, but on macOS, this does not. 这应该可以,但是在macOS上则不能。

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

Note the e? 注意e? Someone on here suggested to add an e, and yes, that works.. but it means it adds the e behind the .txt. 这里有人建议添加一个e,是的,这是可行的..但这意味着它将.txt后面添加了e。 I end up with 2 files, example.txt and example.txte 我最终得到2个文件,例如example.txt和example.txte

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

Note the '' behind -i, and yes, without a space? 注意-i后面的”,是的,没有空格吗? This should work too. 这也应该起作用。 It doesn't, it will complain that command c requires \\ 并非如此,它会抱怨命令c需要\\

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? 在macOS上,在bash shell脚本中,如何简单地用全新的文本行替换.txt文件中的指定文本行-不知道之前的文本行?

If this can be a simple macOS one liner with awk or whatever, that's fine. 如果这可以是带有awk或其他功能的简单macOS衬垫,那就很好。 It doesn't have to be sed. 它不必被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: 在macOS的sed手册页中:

-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: 因此,可以在不保留备份的情况下替换第2行:

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: 如果目标只是替换第2行的内容,那么也可以使用awk ,例如:

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: 在MacOS上带sed-i参数需要备份文件的文件扩展名,例如:

/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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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