从文件中修剪字段

从文件中修剪字段

文件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

相关内容