[英]awk keep header when using IGNORECASE
我有一個 csv 文件我想在特定列columnB
(我的數據集中的第 5 列)中搜索一個字符串(忽略大小寫),並在另一個columnC
(我的數據集中的第 10 列)上應用過濾器。 然后將選定的列保存到文件中。
數據集樣本
columnA columnB columnC columnD
abc Apple 100 today
nbd apple 50 tomorrow
ccc apple 101 today
所需 output
columnB columnC
Apple 100
apple 101
當我使用awk
時的問題我可以 select columnB
,但我不能 output Z01959FB99E4406F3
awk 'BEGIN {IGNORECASE = 1} {if($5 == "Apple") print $0 }' Data.csv> testPipe.txt
我曾嘗試使用NR==1
但由於某種原因它不適用於IGNORECASE
。
我嘗試使用grip
,我可以 output 和 header 但我不能指定columnB
用於字符串匹配。搜索將應用於所有列。
cat Data.csv |{ head -1; grep -I "Apple";} | awk -F',' '{ if ($10 >100 ) { print } }'>testPipe.txt
有沒有辦法結合這兩種方法並獲得所需的 output? 謝謝
使用 function tolower()
:
awk 'NR==1{print; next} tolower($5) == "apple"' file
解釋:
# Print the headers
NR==1 {
print
next
}
# Print the current line if $5 matches the condition
# Note that if there is no action specified, awk will
# use print $0 by default
tolower($5)
如果您想在條件為真時編寫進一步的操作,請將它們放入一個塊中
tolower($5) {
...
}
與僅適用於 GNU awk 的IGNORECASE
相反, tolower()
將適用於awk
的任何版本,因為它是由 POSIX 定義的。
更新:顯然我的回答沒有我想象的那么好,請參閱下面 Ed Morton 的評論。 無論如何,我會保留它,作為“如何不這樣做”。
原始(壞)答案:
在設置 IGNORECASE 之前或之后將以下內容添加到您的 BEGIN 子句中:
getline;
print;
解釋: BEGIN 子句在其他所有內容之前執行一次,因此您也可以在那里處理行,但您必須手動讀取它們。
完整示例:
awk '
BEGIN {
getline;
print;
IGNORECASE = 1;
}
$2 == "apple" && $3 <= 100 {
print $1;
}
'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.