我想列印所有包含單詞的列,例如“西瓜”。A 正在考慮將這兩個公式一起使用,因為它們單獨作業(一個是為檔案中的每一列做一些事情,另一個是檢查列是否包含特定的詞)。
awk '{for(i=1;i<=NF-1;i ) printf $i" "; print $i}' a.csv
awk -F"," '{if ($2 == " watermelon") print $2}' a.csv
但是當我嘗試將它們放在一起時,我的代碼不起作用
#!/bin/bash
awk '{for(i=1;i<=NF-1;i )
awk -F"," '{if ($i == " watermelon")
print $i}' a.csv
}' a.csv
例如這是我的檔案 a.csv
lp, type, name, number, letter
1, fruit, watermelon, 6, a
2, fruit, apple, 7, b
3, vegetable, onion, 8, c
4, vegetable, broccoli, 6, b
5, fruit, orange, 5, c
這是我想得到的結果,同時搜索 word watermelon
name
watermelon
apple
onion
broccoli
orange
uj5u.com熱心網友回復:
$ cat tst.awk
BEGIN { FS=OFS=", " }
NR==FNR {
for (inFldNr=1; inFldNr<=NF; inFldNr ) {
if ( $inFldNr == tgt ) {
hits[inFldNr]
}
}
next
}
FNR==1 {
for (inFldNr=1; inFldNr<=NF; inFldNr ) {
if ( inFldNr in hits ) {
out2in[ numOutFlds] = inFldNr
}
}
}
{
for (outFldNr=1; outFldNr<=numOutFlds; outFldNr ) {
inFldNr = out2in[outFldNr]
printf "%s%s", $inFldNr, (outFldNr<numOutFlds ? OFS : ORS)
}
}
$ awk -v tgt='watermelon' -f tst.awk file file
name
watermelon
apple
onion
broccoli
orange
上述方法與@JamesBrown 的方法之間的主要區別在于,在檔案的第二遍中,我的腳本僅在要輸出的欄位上回圈,而 James 則在所有輸入欄位上回圈,因此在可能的正常情況下會變慢并非所有輸入欄位都必須輸出。
關于printf $i在你的代碼順便說一句-從來沒有做到這一點,總是做printf "%s", $i任何輸入資料,而不是因為當你輸入包含printf格式化字符像前將失敗%s。
uj5u.com熱心網友回復:
這是一個處理資料兩次的方法:
$ awk -F', ' ' # remember to se OFS if you need one
NR==FNR { # on the first run
for(i=1;i<=NF;i ) # find
if($i=="watermelon") # watermelon fields
a[i] # and mark them
next
}
FNR==1 { # in case there were no such field
for(i in a) # test
next # and continue
exit # or exit
}
{ # on the second run
for(i=1;i<=NF;i )
if(i in a)b=b (b==""?"":OFS) $i # buffer those fields for output
print b # and output
b="" # clean that buffer for next record
}' file file
輸出:
name
watermelon
apple
onion
broccoli
orange
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/373332.html
