[英]Parsing multiple CSV files in bash by pattern with counter
假設我有文件
我得到了帶有一點格式的第二列的最后一個值
awk -v max=0 '{if($1>max){want=$2; max=$1}}END{print "x:";print want} ' report-x-1.csv >> test.txt
如何使用任意數量的 .csv 文件執行此操作並在頂部有一個計數器?
awk -v max=0 '{if($1>max){want=$2; max=$1}}END{print "x:";print want} ' report-x-* >> test.txt
只是為第一個文件做一些事情。
我最終需要的是一個像這樣的 .csv 但有任意數量的輸入文件:
x1 , 300
x2 , 250
x3 , 300
y1 , 270
y2 , 250
y3 , 280
編輯:
我還沒有詳細嘗試每個想法,為了更清楚,這里有兩個示例文件
這些文件可以命名為 report-x-1.csv 和 report-y-1.csv,輸出文件應包含兩行 x-1: 156. ... 和 y-1: 300. .... (這是最后一行第二列)
該解決方案應該適用於如上所述的多個輸入文件。
也許嘗試這樣的事情:
for file in $(ls)
do
echo 'Doing something to file:' $file
awk -v max=0 '{if($1>max){want=$2; max=$1}}END{print "x:";print want} ' $file >> test.txt
done
或者可能:
for file in $(ls)
do
if [[ $file == *.csv ]]; then
echo 'Doing something to file:' $file
awk -v max=0 '{if($1>max){want=$2; max=$1}}END{print "x:";print want} ' $file >> test.txt
fi
done
你能不能試試以下。 由於未提供樣品,因此無法對其進行測試。 但這應該比遍歷所有 csv 文件並在每次迭代中調用awk
的for
循環快。
以下是該計划中注意的要點:
for
循環來遍歷.csv
文件,因為awk
能夠做到這一點。x
、 y
值,我也添加了該邏輯。BEGIN
部分設置輸出文件名。awk -v max=0 '
BEGIN{
OFS=" , "
output_file="output.txt"
}
FNR==1{
if(want){
print output":"ORS want > (output_file)
}
split(FILENAME,array,"[-.]")
output=array[2] array[3]
want=max=""
}
{
if($1>max){
want=$2
max=$1
}
}
END{
print output":"ORS want > (output_file)
}
' *.csv
OP 修正了錯別字
要為目錄中的每個文件運行腳本,您可以使用 pipep 文件名並使用xargs -n1
:
echo report-x-*.csv | xargs -n1 awk -v max=0 '{if($1>max){want=$2; max=$1}}END{print "x:";print want}' >> test.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.