使用 sed 在文本文件中添加新行字符

使用 sed 在文本文件中添加新行字符

/etc/securetty我想使用以下命令将以下内容添加到文件中sed

pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9

为此,我编写了以下命令:

sed -i '$a pts/0\\npts/1\\npts/2\\npts/3\\npts/4\\npts/5\\npts/6\\npts/7\\npts/8\\npts/9' /etc/securetty

这给了我输出:

pts/0\npts/1\npts/2\npts/3\npts/4\npts/5\npts/6\npts/7\npts/8\npts/9

我显然在这里错过了一些东西。我的命令可能有什么问题sed

答案1

简单的方法:

for i in {0..9}; do echo "pts/"$i; done >> /etc/securetty

>>- 将输出附加到文件

>- 直接输出到文件(覆盖)

答案2

顺便说一句,如果你想附加到结尾类似这样的现有文件,您既不需要 sed 也不需要 shell 循环。这只是一个命令:

$ printf '%s\n' "pts/"{0..10} >> /etc/securetty

如果你想插入开始您仍然可以使用 printf 来完成文件的操作:

$ cat file1
europe|EU
australia|AU
china|CN
$ printf '%s\n%s\n' "pts/"{0..10} "$(<file1)"
pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9
pts/10
europe|EU
australia|AU
china|CN

/etc/securetty您可以像这样替换文件的内容(甚至sed -i在幕后执行完全相同的工作):

$ printf '%s\n%s\n' "pts/"{0..10} "$(</etc/securetty)" > tmpsecure && mv -f tmpsecure /etc/securetty

选择:

$ { printf '%s\n' "pts/"{0..10}; cat /etc/securetty; } > tmpsecure && mv -f tmpsecure /etc/securetty
# Or
# cat <(printf '%s\n' "pts/"{0..10}) /etc/securetty > tmpsecure && mv tmpsecure /etc/securetty

答案3

它应该是:

sed -i 'a pts/0\npts/1\npts/2\npts/3\npts/4\npts/5\npts/6\npts/7\npts/8\npts/9' /etc/securetty

或者,您可以将内容放入文件中并使用read (r)sed 选项附加到目标文件。

例子:

$ cat input.txt
pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9

$ cat /etc/securetty
This is a dummy file

命令:

sed -i 'r input.txt' /etc/securetty

文件/etc/securetty修改如下:

$ cat /etc/securetty
This is a dummy file
pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9

相关内容