2017-02-22 55 views
-1

我想在Linux中的特定行號處添加一個字符串到文件。我搜查,發現像這樣的命令:將字符串添加到特定行號的文件

sed "5i helloworld" test.txt 

在5號線加helloworld,但我得到了一個錯誤:

sed: command garbled.

似乎對sed的Solaris不支持選項-i。我在這裏測試RedHat。有沒有其他的命令可以在這裏使用?任何其他方式?

+1

您正在使用Linux或Solaris? – miken32

+0

@ miken32 linux在這裏。 – Richard

+0

那麼你會有什麼工作,你爲什麼提到Solaris? – miken32

回答

2

如何鍵入命令如i,ac,舊版seds有點挑剔。嘗試實際續行:

sed '5i\ 
helloworld' test.txt 

i text語法是GNU擴展。 POSIX sed只知道帶有換行符的i\版本。

另外,注意有和-i選項(就地編輯)關於sed i命令 (插入文本)之間的差。


或 「功能」。

+1

_可選reading_:總結術語對話:[_POSIX_ spec](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html)和[_BSD_ Sed m​​an page](https:/ /www.freebsd.org/cgi/man.cgi?query=sed&sektion=&n=1)調用腳本中可用的功能單元 - 例如'i' - 一個_function_和一個_instance of calling_這樣的單元(名稱函數加上它的參數)_command_。相比之下,[_GNU_ Sed的手冊頁](https://www.gnu.org/software/sed/manual/sed.html#Common-Commands)並未作出此區分,而_only_使用術語_command_。 – mklement0

+0

感謝您的意見。現在它適用於我。 – Richard

0

這裏是awk解決方案:

awk 'NR==5{1;print "Hey there this is new text added on line 5"}1' inputfile 
+0

我看到錯誤:awk:第1行附近的語法錯誤 awk:靠近第1行救助 – Richard

+0

@Richard對'awk'版本'GNU Awk 3.1.7'正常工作。你確定它相同或更高? –

+0

感謝您的信息。而且我看到我也有可用的gawk命令。我的gawk是GNU Awk 4.1.0,API:1.0。所以把你的命令改爲gawk爲我工作。所以命令--- gawk'NR == 5 {1; print「嘿,這是在第5行添加的新文本」} 1'測試---在我的服務器上正常工作。我在我的服務器上看到awk和gawk。之前沒有注意到gawk。 – Richard

相關問題