使用 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

相關內容