我想洗掉文本中的“_”和“:”,然后在 AWK 中將文本轉換為小寫,但無法正常作業。這是一個簡單的data.txt檔案:
Count_Part:AA,1,2,3,4,5
Name_Date:BB,4,5,6,7,8
和我的腳本process.awk:
BEGIN{
FS=",";
}
{
print("raw -->", $1);
replaced=$gsub(/_|:/, "", $1);
print("replacement -->", $replaced);
lowered=$tolower($replaced);
print("to lowercase -->", $lowered);
print("\n");
}
但我從中得到的cat data.txt | awk -f process.awk是,這不是我所期望的:
raw --> Count_Part:AA
replacement --> CountPartAA
to lowercase --> CountPartAA 1 2 3 4 5
raw --> Name_Date:BB
replacement --> 6
to lowercase -->
我想知道 1)為什么CountPartAA不列印為countpartaa,以及 2)為什么 data.txt 的第二行沒有與第一行類似的輸出。
我懷疑這是由于變數賦值和函式回傳語法,但我無法讓它作業。我的預期輸出是這樣的:
raw --> Count_Part:AA
replacement --> CountPartAA
to lowercase --> countpartaa
raw --> Name_Date:BB
replacement --> NameDateBB
to lowercase --> namedatebb
請幫助。謝謝!
uj5u.com熱心網友回復:
你很接近,需要洗掉$函式和變數上的符號 $1 :
BEGIN{
FS=",";
}
{
print("raw -->", $1);
gsub(/_|:/, "", $1); # return integer and modify $1 directly
replaced=$1
print("replacement -->", replaced);
lowered=tolower(replaced);
print("to lowercase -->", lowered);
print("\n");
}
輸出
raw --> Count_Part:AA
replacement --> CountPartAA
to lowercase --> countpartaa
raw --> Name_Date:BB
replacement --> NameDateBB
to lowercase --> namedateb
uj5u.com熱心網友回復:
你的意思是這樣嗎?
{m,n,g}awk '$!NF=tolower($!(NF=NF))' FS='[_:]' OFS=
countpartaa,1,2,3,4,5
namedatebb,4,5,6,7,8
uj5u.com熱心網友回復:
如前所述,您不應該在函式呼叫之前使用$,所以不要:
replaced=$gsub(/_|:/, "", $1);
反而
replaced=gsub(/_|:/, "", $1);
您還誤解了GNU AWK 用戶指南中的gsub作業原理
gsub(regexp, replacement [, target])搜索所有最長、最左邊、不重疊的匹配子字串的目標,并用替換替換它們。(...)該函式回傳所做的替換次數。(...)
gsub()
因此,如果您只需要更改字串,您可能會忽略回傳值,例如,如果您需要從第一列中洗掉數字,您可能只是這樣做
awk '{gsub(/[0-9]/, "", $1);print}' file.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487543.html
