[英]Modify lines in a file between two matching strings using sed or awk in bash
[英]Find and append to Text Between Two Strings or Words using sed or awk
我正在尋找一個sed
,我可以識別兩個指示器之間的所有文本,然后用占位符替換它。
例如,第一個指標是單詞列表
(no|noone|haven't)
第二個指標是標點符號列表:
(.|,|!)
從輸入文本,如
“沒有人理解情節。沒有故事情節。我沒有向朋友推薦這部電影!你明白了嗎?”
期望的結果是。
“沒人理解_AFFIX me_AFFIX。沒有storyline_AFFIX。我沒有推薦_AFFIX this_AFFIX movie_AFFIX to_AFFIX my_AFFIX friends_AFFIX!你明白了嗎?”
我知道有以下sed
:
sed -n '/WORD1/,/WORD2/p' /path/to/file
它承認兩個指標之間的內容。 我還發現了很多偉大的信息和資源在這里 。 但是,我仍然找不到一種方法來將詞綴附加到兩個指示符之間出現的每個文本標記。
我也考慮過使用awk
,比如
awk '{sub(/.*indic1 /,"");sub(/ indic2.*/,"");print;}' < infile
但是,它不允許我附加詞綴。
有沒有人建議這樣做,無論是awk
還是sed
?
Perl救援!
perl -pe 's/(?:no(?:one)?|haven'\''t)\s*\K([^.,!]+)/
join " ", map "${_}_AFFIX", split " ", $1/egi
' infile > outfile
\\K
匹配左側的內容,但將其從替換中排除。 在這種情況下,它會驗證第一個指標。 ( \\K
需要Perl 5.10+。) /e
將替換部件評估為代碼。 在這種情況下,代碼在空格上拆分$1
,map將_AFFIX
添加到每個成員,並且join
將它們連接回一個字符串。 這是一個詳細的awk命令:
s="Noone understands the plot. There is no storyline. I haven't recommended this movie to my friends! Did you understand it?"
awk -v IGNORECASE=1 -v kw="no|noone|haven't" -v pct='\\.|,|!' '{
a=0
for (i=2; i<=NF; i++) {
if ($(i-1) ~ "\\y" kw "\\y")
a=1
if (a && $i ~ pct "$") {
p = substr($i, length($i), 1)
$i = substr($i, 1, length($i)-1)
}
if (a)
$i=$i "_AFFIX" p
if(p) {
p=""
a=0
}
}
} 1'
輸出:
Noone understands_AFFIX the_AFFIX plot_AFFIX. There is no storyline_AFFIX. I haven't recommended_AFFIX this_AFFIX movie_AFFIX to_AFFIX my_AFFIX friends_AFFIX! Did you understand it?
更緊湊的awk
$ awk 'BEGIN{RS=ORS=" ";s="_AFFIX"}
/[.,!]$/{f=0; $0=gensub(/(.)$/,"s\\1","g")}
f{$0=$0s}
/Noone|no|haven'\''t/{f=1}1' story
沒人理解_AFFIX the_AFFIX plot_AFFIX。 沒有storyline_AFFIX。 我沒有推薦_AFFIX this_AFFIX movie_AFFIX to_AFFIX my_AFFIX friends_AFFIX! 你明白了嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.