2015-05-22 62 views
5

前插入行我有文件與以下信息命令到第一場比賽

testing 
testing 
testing 

我想用SED或任何Linux命令

需要插入第一個測試字之前一個字(測試)得到這樣

tested 
testing 
testing 
testing 

感謝

+1

@ mklement0:是的,我看到它之後。我想這就是爲什麼我不能在凌晨4點閱讀問題:)。我的錯。謝謝! –

回答

4

究竟:

sed '0,/testing/s/testing/tested\n&/' file 

對於包含線 「測試」:

sed '0,/.*testing.*/s/.*testing.*/tested\n&/' file 

對於線用 「測試」

sed '0,/^testing.*/s/^testing.*/tested\n&/' file 

佛開始恢復系以「測試」結尾:

sed '0,/.*testing$/s/.*testing$/tested\n&/' file 

要更新結果文件的內容加上「-i」,例如:

sed -i '0,/testing/s/testing/tested\n&/' file 
6

輸出這可能會爲你工作(GNU SED):

sed -e '/testing/{itested' -e ':a;n;ba}' file 

插入testedtesting第一場比賽之前,然後使用循環讀取/打印文件的剩餘部分。

或者使用GNU具體:

sed '0,/testing/itested' file 
5

爲了提供基於awk的替代方案,是比較容易理解:

awk '!found && /testing/ { print "tested"; found=1 } 1' file 
  • found是用來保持跟蹤是否初審已找到testing(變量found,因爲任何Awk變量,默認爲0,即false在布爾上下文中)。因此
  • /testing/匹配包含testing第一線,並處理相關聯的塊:
    • { print "tested"; found=1 }打印所需的文字,並且設置所述第一testing線已經發現
  • 1是一個標誌通用簡寫爲{ print },即簡單地打印當前輸入行。