簡體   English   中英

如何使用 awk 顯示包含特定單詞的文件列

[英]How to display file columns containing a specific word using awk

我想打印所有包含單詞的列,例如“西瓜”。 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 西瓜

name
watermelon
apple
onion
broccoli
orange

這是處理數據兩次的一個:

$ 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

Output:

name
watermelon
apple
onion
broccoli
orange
$ 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 的方法之間的主要區別在於,在文件的第二遍中,我的腳本僅循環遍歷字段為 output 而 James 循環遍歷所有輸入字段,因此在可能的正常情況下會變慢並非所有輸入字段都必須是 output。

關於printf $i在您的代碼中順便說一句 - 永遠不要這樣做,總是對任何輸入數據執行printf "%s", $i %s ,因為當您的輸入包含 ZAFA0FF8B27B87666A6BDE87251C 5.FDEZ 格式時,前者將失敗

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM