如何從具有特定字串的行開頭刪除整個文本

如何從具有特定字串的行開頭刪除整個文本

我用來sed -n '/string/,$p' file >> otherfile將文字從具有特定字串的行複製到另一個文件。

現在我想刪除原始文件中複製的文字。我用 sed 和 awk 嘗試了不同的方法,但沒有任何效果。

如何使用 sed 刪除檔案中包含特定字串的起始行文字?

texta

texta1

textb    <- string, delete rest of the text from here

textb1

textc

textc1

或者使用 sed 進行剪切而不是複製會更容易嗎?

答案1

你可以w將指定範圍的行寫入一個新文件,然後d刪除範圍 - 棘手的部分是防止d命令被視為輸出檔案名稱的一部分。在 GNU sed 中,您可以透過使用以下命令將寫入和刪除分成單獨的表達式來做到這一點-e

重要提示:這將截斷otherfile而不是附加到它

sed -i.bak -e '/string/,${w otherfile' -e 'd;}' file

答案2

或使用ed!

ed -s file <<< $'/textb/,$w otherfile\n/textb/,$d\nw\nq'

鑑於您的意見文件的:

texta

texta1

textb    <- string, delete rest of the text from here

textb1

textc

textc1

執行ed命令後,文件變成:

texta

texta1

(末尾有一個空行,在此處的格式中消失);和其他文件包含:

textb    <- string, delete rest of the text from here

textb1

textc

textc1

命令ed是:

  • /textb/,$w otherfile-- 將行範圍寫入其他文件
  • /textb/,$d-- 刪除該範圍的行
  • w-- 將更改的檔案寫入磁碟
  • q——退出編輯

答案3

如果您使用此命令sed -n '/string/,$p' file >> otherfile從一個命令中提取所有行含有 string到檔案末尾 ( $) 到 otherfile 檔案。

提取其補碼最簡單的方法是對匹配項進行補碼:

sed '/string/,$d' file >> someOtherDifferentFile

如果您想要/需要更新原始文件,只需將結果複製回來即可。

這就是-ised 選項的作用,因此,這將更新原始檔案:

sed -i.bak '/string/,$d' file

相關內容