從文件中修剪欄位

從文件中修剪欄位

文件a.txt的內容

Event: "112506400","17","2016/07/13-15-25-59.00",,,,,,,,,,,"112506400","115101234","02:00:00","pc","abc","4194","file_nam","F",,,"LA
",,"jk","123",,,,,,,,,,

我需要一個沒有 $20 ( file_name ) 重定向到 asort.txt 的檔案。目前我正在使用以下命令,是否有任何簡短命令

cat a.txt | grep Event: |awk -F, '{print $1","$2","$3","$4","$5","$6","$7","$8","$9","$10","$11","$12","$13","$14","$15","$16","$17","$18","$19","$21","$22","$23","$24","$25","$26","$27","$28","$29","$30","$31","$32","$33","$34","$35","$36","$37}'> asort.txt

答案1

也許 cut 命令可以做到:

cat a.txt | cut -d "," -f 1-19,21-37

因此,您可以跳過欄位 #20,假設逗號是穩定的分隔符號。

答案2

這應該有效:

grep Event: a.txt | awk 'BEGIN{FS=OFS=","}{$20=""; print}' > asort.txt

答案3

sed

$ echo 'a,,b,c,d' | sed -E 's/^(([^,]*,){2})[^,]*,/\1/'
a,,c,d
$ echo 'a,,b,c,d' | sed -E 's/^(([^,]*,){3})[^,]*,/\1/'
a,,b,d
  • [^,]*,零個或多個非逗號文字後面跟著逗號
  • {2}{3}前一組兩三次,用列號減一刪除

與 類似perl,只是我們可以重複使用正規表示式模式

$ # (?2) refers to ([^,]*,)
$ echo 'a,,b,c,d' | perl -pe 's/^(([^,]*,){2})(?2)/$1/'
a,,c,d
$ echo 'a,,b,c,d' | perl -pe 's/^(([^,]*,){3})(?2)/$1/'
a,,b,d

$ # golfed with lookbehind
$ echo 'a,,b,c,d' | perl -pe 's/^([^,]*,){2}\K(?1)//'
a,,c,d
$ echo 'a,,b,c,d' | perl -pe 's/^([^,]*,){3}\K(?1)//'
a,,b,d

相關內容