[英]removing lines between two patterns (not inclusive) with sed
行
我知道這是一個微不足道的問題,但是:如何從兩個已知模式/單詞之間的文件中刪除行:
模式1
垃圾
模式2
獲得:
模式1
模式2
有沒有人知道學習 sed 的好(簡單的書面!)資源? 有很多明確的例子嗎?
sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*\n//}; p' inputfile
說明:
/pattern1/{ # if pattern1 is found
p # print it
:a # loop
N # and accumulate lines
/pattern2/!ba # until pattern2 is found
s/.*\n// # delete the part before pattern2
}
p # print the line (it's either pattern2 or it's outside the block)
編輯:
某些版本的sed
必須用勺子喂食:
sed -n -e '/pattern1/{' -e 'p' -e ':a' -e 'N' -e '/pattern2/!ba' -e 's/.*\n//' -e '}' -e 'p' inputfile
這可能對你有用:
sed '/pattern1/,/pattern2/{//!d}' file
awk '/pattern1/{g=1;next}/pattern2/{g=0;next}g' file
這個sed代碼也可以運行:
sed '/PATTERN1/,/PATTERN2/d' FILE
您也可以使用Unix文本編輯器編輯:
echo '
pattern1
garbage
pattern2
' > test.txt
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s test.txt &>/dev/null
H
/pattern1/+1,/pattern2/-1d
wq
EOF
有關更多信息,請參閱: 使用腳本中的ed文本編輯器編輯文件
對我來說,“sed '\/PATTERN1\/,\/PATTERN2\/d' FILE”正在工作(在 PATTERN1 和最后一次出現的 PATTERN2 之間)
但我有一個問題:如果 PATTERN2 多次出現,我怎樣才能讓它工作直到第一次出現 PATTERN2,而不是最后一次?
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.