![](/img/trans.png)
[英]How to use gsub in awk to find and replace (“./”) and (“.txt”) characters within a file
[英]Concatenating black-list to use as AWK gsub regex in CSV file
我正在嘗試使用腳本從 CSV 文件的特定列中刪除 blacklist.txt 文件中出現的任何字符串。
通過許多版本的反復試驗,我發現以下 AWK 正則表達式可以在不匹配子字符串的情況下工作。
將換行符分隔的 txt 文件轉換為正則表達式: list="$(cat blacklist.txt | tr "\n" "|" | sed 's/.$//')"
這給出了類似於此的 output: already|also|although|always|am|among|amongst|amoungst|amount|an|and|another|any|anyhow|anyone|anything|anyway|anywhere
然后我嘗試在 awk 替換命令中使用此變量,使用"\\<(word|word)>\\ *"
正則表達式格式以避免 substring 匹配。
這看起來如下:
awk -F, -v list=$list 'BEGIN{ re = "\x22\\\\<("list")\\\\> *\x22"} { gsub(re,"", $2);} 1 ' OFS=',' test.csv
這本身不起作用。 但是,如果我打印從此命令生成的正則表達式:
awk -F, -v list=$list 'BEGIN{ re = "\x22\\\\<("list")\\\\> *\x22"} { gsub(re,"", $2); print re} 1 ' OFS=',' test.csv
我得到一個re
的格式:
"\\<(a|about|above|across|after|afterwards|again|against|all|almost|alone|along|already|also|although|always|am|among|amongst|amoungst|amount|an|and|another|any|anyhow|anyone|anything|anyway|anywhere)\\> *"
如果我將其復制並粘貼到 awk 命令中,替換 gsub 中的re
變量,那么它可以工作!
當作為正則表達式粘貼的變量的直接 output 確實有效時,我無法弄清楚為什么正則表達式不能作為變量工作。
foobar,a house car,a foobar, foobar foobar
foobar,a house car,a foobar, foobar foobar
foobar,a house car,a foobar, foobar foobar
foobar,a house car,a foobar, foobar foobar
awk -F, -v list=$list 'BEGIN{ re = "\x22\\\\<("list")\\\\> *\x22"} { gsub(re,"", $2);} 1 ' OFS=',' test.csv
foobar,a house car,a foobar, foobar foobar
foobar,a house car,a foobar, foobar foobar
foobar,a house car,a foobar, foobar foobar
foobar,a house car,a foobar, foobar foobar
awk -F, -v list=$stop_word_list '{ gsub("\\<(a|about|above|across|after|afterwards|again|against|all|almost|alone|along|already|also|although|always|am|among|amongst|amoungst|amount|an|and|another|any|anyhow|anyone|anything|anyway|anywhere)\\> *","", $2);} 1 ' OFS=',' test.csv
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
請注意,“a”從第二列中消失了,但沒有從第三列中消失,並且“car”內部的 a 也不匹配。
請注意,blacklist.txt 文件比我在此處提供的文件要長一些,並且我沒有在列入黑名單的單詞中進行硬編碼的選項,因為它們可能會被換出。
在 OP 的代碼中, re = "\x22...\x22"
將實際的雙引號嵌入到變量re
中,這反過來又告訴gsub()
在$2
中查找實際的雙引號。
雖然剝離\x22
可能會有所幫助,但我將選擇一種稍微不同的方法......
一種在gsub()
調用中構建正則表達式的awk
解決方案:
list='a|about|above|across|after'
awk -v list="${list}" 'BEGIN {FS=OFS=","} {gsub("\\<("list")\\> *","",$2)} 1' test.csv
這會產生:
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
如果 OP 在一些地方需要正則表達式,我們仍然可以使用以下內容構建re
變量:
awk -v list="${list}" 'BEGIN {FS=OFS=","; re="\\<("list")\\> *"} {gsub(re,"",$2)} 1' test.csv
這也產生:
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
foobar,house car,a foobar, foobar foobar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.