簡體   English   中英

在 shell 腳本中使用 sed 向文件添加一行

[英]Adding a line to a file using sed in a shell script

我有一個有 109 行的文件。

我在下面顯示的行上執行兩個操作。

# Delete line 74
sed -i '74d' Test.txt

# Add the entry to line 109
  sed -i "109iThis is the string" Test.txt

我看到第 74 行從我的 Test.txt 中刪除,但由於某些原因,現在我的 Test.txt 只有 108 行,我沒有看到This is the string添加到第 109 行This is the string

我不確定錯誤是什么。 我該如何解決?

你可以使用這個 POSIX sed命令:

sed -i.bak '74d; $ a\
This is the string
' file

這將從文件中刪除第 74 行並在最后添加一行並將保存內聯更改。

請注意,這也適用於gnu-sed

如果刪除一行,文件只剩下 108 行。 相應地更正您的第二個命令:

sed -i "108iThis is the string" Test.txt

喬納森已經提到了使用sed -i的潛在問題(非標准,在支持時以不同的方式表現,具體取決於實現等)。 通過使用ed編輯文件來避免它們:

ed -s Test.txt <<EOF
109a
This is the string
.
74d
w
EOF

請注意這是如何追加,然后刪除。 因為ed作用於整個文件,而不是行流,所以作用於特定行的命令可以按任何順序進行。

行號 109 不存在(您刪除了一個,109-1=108),您必須先添加它,然后才能在其中輸入文本。

解決方案: sed -i '$ a <text>' Test.txt新行將與所選文本一起添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM