我有以下名為 st.txt 的檔案:
Item Type Amount Date
Petrol expense -160 2020-01-23
Electricity expense -200 2020-03-24
Electricity expense -200 2020-04-24
Trim line expense -50 2020-05-30
Martha Burns income 150 2021-03-11
Highbury shops income 300 2021-03-14
我想按日期對資料進行排序并列印除第一行之外的所有資料。以下命令有效:
awk -F '\t' 'NR>1{print $4"\t"$1"\t"$2"\t"$3}' st.txt | sort -t"-" -n -k1 -k2 -k3
那么輸出是:
2020-01-23 Petrol expense -160
2020-03-24 Electricity expense -200
2020-04-24 Electricity expense -200
2020-05-30 Trim line expense -50
2021-03-11 Martha Burns income 150
2021-03-14 Highbury shops income 300
如何撰寫此命令,這樣我就不必重新排列列,使日期欄位保持在 $4?我嘗試了以下方法,但它不起作用:
awk -F '\t' 'NR>1{print $0}' st.txt | sort -t"-" -n -k 4,1 -k 4,2 -k 4,3
日期不使用此命令排序。
輸出應該是:
Petrol expense -160 2020-01-23
Electricity expense -200 2020-03-24
Electricity expense -200 2020-04-24
Trim line expense -500 2020-05-30
Martha Burns income 150 2021-03-11
Highbury shops income 300 2021-03-14
uj5u.com熱心網友回復:
假設您的輸入檔案中的欄位是制表符分隔的,因為您的代碼表明它們是:
$ tail -n 2 file | sort -t$'\t' -k4
Petrol expense -160 2020-01-23
Electricity expense -200 2020-03-24
Electricity expense -200 2020-04-24
Trim line expense -50 2020-05-30
Martha Burns income 150 2021-03-11
Highbury shops income 300 2021-03-14
uj5u.com熱心網友回復:
使用 GNU awk:
awk -F '\t' 'NR>1{a[$4]=$0} END{PROCINFO["sorted_in"] = "@ind_str_asc"; for(i in a){print a[i]}}' file
輸出:
汽油費-160 2020-01-23 電費-200 2020-03-24 電費-200 2020-04-24 修剪線費用-50 2020-05-30 瑪莎伯恩斯收入150 2021-03-11 海布里店鋪收入300 2021-03-14
uj5u.com熱心網友回復:
鑒于:
$ awk '{gsub(/\t/,"\\t")} 1' file
Item\tType\tAmount\tDate
Petrol\texpense\t-160\t2020-01-23
Electricity\texpense\t-200\t2020-03-24
Electricity\texpense\t-200\t2020-04-24
Trim line\texpense\t-50\t2020-05-30
Martha Burns\tincome\t150\t2021-03-11
Highbury shops\tincome\t300\t2021-03-14
您可以在POSIX awk 中使用Decorate / Sort / Undecorate模式:
awk 'BEGIN{FS=OFS="\t"} FNR>1{print $4, $0}' file | sort | cut -f 2-
或者使用適當的 CSV 決議器集來使用 a\t而不是逗號。Ruby 是最簡單的:
ruby -r csv -e '
options={:col_sep=>"\t", :headers=>true, :return_headers=>true}
data=CSV.parse($<.read, **options).to_a
header=data.shift.to_csv(**options)
data.sort_by{|r| r[3]}.each{|r| puts r.to_csv(**options)}
' file
要么列印:
Petrol expense -160 2020-01-23
Electricity expense -200 2020-03-24
Electricity expense -200 2020-04-24
Trim line expense -50 2020-05-30
Martha Burns income 150 2021-03-11
Highbury shops income 300 2021-03-14
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405603.html
標籤:
上一篇:實作歸并排序演算法
