[英]replace a specific pattern in a column using awk or gsub
我有一個制表符分隔的文件,其中包含如下所示的列:
1 2 3 Score\x3e366\x3bName\x3elod\x3e41
3 5 6 Score\x3e366\x3bName\x3elod\x3e41
我需要將'\\ x3e'替換為'=',並將'\\ x3b'替換為';' 在第四列。 輸出應如下所示:
1 2 3 Score=366;Name=lod=41
3 5 6 Score=366;Name=lod=41
有人可以幫助awk / gsub來做到這一點。 提前致謝。
sed
怎么樣?
more file.txt | sed -e s/\\\\x3e/=/g | sed -e s/\\\\x3b/\;/g
誠然,這巧妙地假設了那些char序列不會出現在第3列之外的任何地方,但是如果允許的話,上面的內容應該對您有用。
$ awk '{col=$4; gsub(/\\x3e/,"=",col); gsub(/\\x3b/,";",col); sub(/[^[:space:]]+$/,col)} 1' file
1 2 3 Score=366;Name=lod=41
3 5 6 Score=366;Name=lod=41
一般情況下,需要替換的列不是該行的最后一列:
$ cat file
1 2 3 Score\x3e366\x3bName\x3elod\x3e41 foo
3 5 6 Score\x3e366\x3bName\x3elod\x3e41 bar
是這樣的(將GNU awk用於gensub()並分成幾行以提高可讀性):
$ awk -v n=4 '{
col = $n
gsub(/\\x3e/,"=",col)
gsub(/\\x3b/,";",col)
print gensub("(\\s*)((\\S+\\s+){"n-1"})\\S+(.*)","\\1\\2" col "\\4","")
}' file
1 2 3 Score=366;Name=lod=41 foo
3 5 6 Score=366;Name=lod=41 bar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.