【问题标题】:sed add lines before end of filesed 在文件末尾添加行
【发布时间】:2014-12-04 21:22:11
【问题描述】:

我正在尝试通过 shell 在 limits.conf 文件的末尾添加 2 行。

我写道:

 sudo sed '$ \\*                hard    nofile          128000\n \\*                soft    nofile          128000 ' /etc/security/limits.conf 

但是我得到:

sed:-e 表达式#1,字符 3:未知命令:`\'

我也试过了:

sudo sed '$ \*                hard    nofile          128000\n \*                soft    nofile          128000 ' /etc/security/limits.conf`

我得到同样的错误

我怎样才能简单地添加:

*                hard    nofile          128000
*                soft    nofile          128000

到最后一行? (因为文件末尾是#END FILE

【问题讨论】:

标签: regex bash sed


【解决方案1】:

可以使用sed的i命令:

sed '$ i\
*                hard    nofile          128000\
*                soft    nofile          128000
' /etc/security/limits.conf

结果:

...
#ftp             hard    nproc           0
#ftp             -       chroot          /ftp
#@student        -       maxlogins       4

*                hard    nofile          128000
*                soft    nofile          128000
# End of file

如果有更多行,则在i\ 之后添加以\ 结尾的每一行。

【讨论】:

  • 我正在尝试在 shell 中使用它 - 而不是一行中的脚本。我该怎么做?我的意思是,在我看来,您在新行中添加了星星
  • 是什么 |头-4在开头是为了什么?为什么 nofile 写了两次?
【解决方案2】:

从 anubhava 对Add two consecutive lines in sed 的回答中可以看出,您可以说:

sed '/#END FILE/a\
*                hard    nofile          128000\
*                soft    nofile          128000
' your_file

单线:

sed '/#END FILE/a\ *                hard    nofile          128000\n *                soft    nofile          128000 ' file

注意使用\n 来表示新行。

请注意,您只使用了$,而您必须说'$a\ 才能附加文本。

来自man sed

零地址或单地址命令

一个\

text 附加文本,每个嵌入的换行符前面都有一个 反斜杠

这种方法的问题在于它在 #END FILE 之后写入。为了让它写before,我们可以用tac反向读取文件:

tac a | sed '/#END FILE/a\ *                hard    nofile          128000\n *                soft    nofile          128000 ' | tac

测试

$ cat a
hello
#END FILE
$ tac a | sed '/#END FILE/a\ *                hard    nofile          128000\n *                soft    nofile          128000 ' | tac
hello
*                soft    nofile          128000 
*                hard    nofile          128000
#END FILE

最后,要进行就地编辑,请使用-i。以下代码将替换file 中的内容并创建一个file.bak 备份文件:

sed -i.bak '...' file

【讨论】:

  • 1. id 也不会更改文件,而是将其输出写入控制台 2。它会将其添加到文件的末尾,而不是最后一行之前的行,因为文件以 File 的 #END 结束,我想写它之前
  • @Dejel for 1. 你必须使用-i,这很简单。但首先你必须测试它是否正常工作。
  • @Dejel 不错!我还指出了如何改用tac
猜你喜欢
  • 2017-10-14
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 2013-04-05
相关资源
最近更新 更多