bash unix 命令行,用于使用 <br> 内联替换文件中的所有换行符\n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3498799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:30:46  来源:igfitidea点击:

unix commandline for inline replacement of all newlines in file with <br>\n

bashunixcommand-linesed

提问by DrMHC

sed 's/$/<br>/' mytext.txt

worked but output it all on the command line. I want it to just do the replacement WITHIN the specified file itself. Should I be using another tool?

工作但在命令行上输出它。我希望它只是在指定的文件本身内进行替换。我应该使用其他工具吗?

回答by camh

If you have gnu sed, you can use the -ioption, which will do the replacement in place.

如果您有 gnu sed,您可以使用该-i选项,它将在适当的位置进行替换。

sed -i 's/$/<br>/' mytext.txt

Otherwise you will have to redirect to another file and rename it over the old one.

否则,您将不得不重定向到另一个文件并将其重命名为旧文件。

sed 's/$/<br>/' mytext.txt > mytext.txt.new && mv mytext.txt.new mytext.txt

回答by bashfu

Just for completeness. On Mac OS X (which uses FreeBSD sed) you have to use an additional null-string "" for in-place file editing without backup:

只是为了完整性。在 Mac OS X(使用 FreeBSD sed)上,您必须使用额外的空字符串 "" 进行就地文件编辑而无需备份:

sed -i "" 's/$/<br>/' mytext.txt

As an alternative to using sed for no-backup in-place file editing, you may use ed(1), which, however, reads the entire file into memory before operating on it.

作为使用 sed 进行无备份就地文件编辑的替代方法,您可以使用 ed(1),但是,它会在对其进行操作之前将整个文件读入内存。

printf '%s\n' H 'g/$/s//<br>/g' ',p' | ed -s test.file  # print to stdout

printf '%s\n' H 'g/$/s//<br>/g' wq | ed -s test.file  # in-place file edit

For more information on ed(1) see:

有关 ed(1) 的更多信息,请参阅:

"Editing files with the ed text editor from scripts",

"使用 ed 文本编辑器从脚本编辑文件",

http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed

http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed

回答by paxdiablo

If you have an up-to-date sed, just use sed -ior sed --in-place, which will modify the actual file itself.

如果您有最新的sed,只需使用sed -ised --in-place,这将修改实际文件本身。

If you want a backup, you need to supply a suffix for it. So sed -i.bakor sed --in-place=.bakwill create a backup file with the .baksuffix.

如果需要备份,则需要为其提供后缀。所以sed -i.bakorsed --in-place=.bak会创建一个带有.bak后缀的备份文件。

Use this! Seriously! You'll appreciate it a lot the first time you damage your file due to a mistyped sedcommand or wrong assumption about the data in the file.

用这个!严重地!当您第一次由于输入错误的sed命令或对文件中数据的错误假设而损坏文件时,您会非常感激。

回答by t0mm13b

Use the redirection symbol i.e.

使用重定向符号即

sed 's/$/<br>/' mytext.txt > mytext2.txt && mv mytext2.txt mytext.txt