2017-07-20 26 views
1

如果我有像格式的標籤delimeted數據文件input.dat如何處理穿過管道的多個字段?

#id acct name city   age 
12 100290 Sally San Francisco 24 
15 102911 Jerry Sacramento 40 
99 102134 Amir Eureka  82 

我可以用cut(1)或類似的東西跑每場多處理功能EX :(lookup_id, scrub_acct, scrub_name, lookup_city, scrub_age)作爲數據運行通過管道?

這很容易有一個字段來做到這一點:

cat input.dat | cut -f1 | lookup_id > output.dat

,但我不知道是否有辦法做到這一點每場,並有重定向到output.dat結果。

#id acct name city   age 
AA XXXXX0 SXXXX city-57  20s 
AC XXXXX1 JXXXX city-29  40s 
AF XXXXX4 AXXXX city-100  80s 

也許前題是你可以嗎?

,我也在考慮如何paste(1)可能只是膠柱一起回來的替代,但也許有更好的方法。

+1

我建議採取看看'awk'。 – Cyrus

+0

好點啊,我想你可以運行在各領域的功能,並揭開序幕子shell。有沒有辦法做到這一點切割? Awk有時候就是這樣一個野獸。 @Cyrus – qodeninja

+0

所以'lookup_id,scrub_acct,scrub_name,lookup_city,scrub_age'是外殼的功能呢? – anubhava

回答

2

通常更容易處理的行,列數據awk但由於外殼功能受累最好是在外殼本身來處理這個問題。

假設lookup_id, scrub_acct, scrub_name, lookup_city, scrub_age是被從標準可以創建他們的數組,並調用它們,同時通過從輸入文件中的每個記錄循環讀取輸入殼函數或腳本:

# example shell functions 
lookup_id() { read str; printf "lookup_id: %s\n" "$str"; } 
scrub_acct() { read str; printf "scrub_acct: %s\n" "$str"; } 
scrub_name() { read str; printf "scrub_name: %s\n" "$str"; } 
lookup_city() { read str; printf "lookup_city: %s\n" "$str"; } 
scrub_age() { read str; printf "scrub_age: %s\n" "$str"; }  

# array of functions or scripts to be invoked 
fnarr=(lookup_id scrub_acct scrub_name lookup_city scrub_age) 

# main processing 
while IFS=$'\t' read -ra ary; do 
    for ((i=0; i<${#ary[@]}; i++)); do 
     # call function for each field value 
     "${fnarr[i]}" <<< "${ary[i]}" 
    done 
    echo '=============================' 
done < <(tail -n +2 file) 

輸出:

lookup_id: 12 
scrub_acct: 100290 
scrub_name: Sally 
lookup_city: San Francisco 
scrub_age: 24 
============================= 
lookup_id: 15 
scrub_acct: 102911 
scrub_name: Jerry 
lookup_city: Sacramento 
scrub_age: 40 
============================= 
lookup_id: 99 
scrub_acct: 102134 
scrub_name: Amir 
lookup_city: Eureka 
scrub_age: 82 
============================= 
+1

變量替代,很聰明。你使用它作爲一種調度器,感謝這個想法! – qodeninja

+1

' 「$ {fnarr [I]}」 <<< 「$ {進制[I]}」',更有效率? – codeforester

+0

是的沒錯,它避免了子shell(編輯) – anubhava

1

嘗試這樣使用awk:

awk -F'\t' '{system("lookup_id " $1); printf("\t"); \ 
      system("scrub_acct " $2); printf("\t"); \ 
      ... 
      }' input.dat