简体   繁体   English

使用awk提取包含空格的列

[英]Using awk to extract a column containing spaces

I'm looking for a way to extract the filename column from the below output. 我正在寻找一种从以下输出中提取文件名列的方法。

    2016-02-03 08:22:33     610540 vendor_20160202_67536242.WAV
    2016-02-03 08:19:25     530916 vendor_20160202_67536349.WAV
    2016-02-03 08:17:10    2767824 vendor_20160201_67369072 - cb.mp3
    2016-02-03 08:17:06     368928 vendor_20160201_67369072.mp3

One of the files has spaces in the name which is causing issues with my current commmand 其中一个文件的名称中包含空格,这导致我当前的命令出现问题

awk '{print $4}'

How would I treat a column with spaces as a single column? 如何将带有空格的列视为单个列?

awk to the rescue! awk解救!

$ awk '{for(i=4;i<NF;i++) printf "%s", $i OFS; 
        printf "%s", $NF ORS}' file

vendor_20160202_67536242.WAV
vendor_20160202_67536349.WAV
vendor_20160201_67369072 - cb.mp3
vendor_20160201_67369072.mp3

or alternatively, 或者,

$ awk '{for(i=5;i<=NF;i++) $4=$4 OFS $i; print $4}' file   

if your file format is fixed perhaps using the structure is a better idea 如果您的文件格式是固定的,则最好使用结构

$ cut -c36- file

vendor_20160202_67536242.WAV
vendor_20160202_67536349.WAV
vendor_20160201_67369072 - cb.mp3
vendor_20160201_67369072.mp3

You could just delete the first 3 space-then-nonspace blocks: 您可以删除前3个space-then-nonspace块:

$ awk '{sub(/^[[:space:]]*([^[:space:]]+[[:space:]]+){3}/,"")}1' file
vendor_20160202_67536242.WAV
vendor_20160202_67536349.WAV
vendor_20160201_67369072 - cb.mp3
vendor_20160201_67369072.mp3

but it looks like you have fixed width fields so to print the last "field" you could just do: 但您似乎拥有固定的宽度字段,因此可以打印最后一个“字段”:

$ awk '{print substr($0,32)}' file
vendor_20160202_67536242.WAV
vendor_20160202_67536349.WAV
vendor_20160201_67369072 - cb.mp3
vendor_20160201_67369072.mp3

but in general use GNU awk's FIELDWIDTHS: 但通常使用GNU awk的FIELDWIDTHS:

$ gawk -v FIELDWIDTHS='10 9 11 9999' '
     {for (i=1;i<=NF;i++) { gsub(/^ +| +$/,"",$i); print NR, NF, i, "<" $i ">" } print "---"}
  ' file
1 4 1 <2016-02-03>
1 4 2 <08:22:33>
1 4 3 <610540>
1 4 4 <vendor_20160202_67536242.WAV>
---
2 4 1 <2016-02-03>
2 4 2 <08:19:25>
2 4 3 <530916>
2 4 4 <vendor_20160202_67536349.WAV>
---
3 4 1 <2016-02-03>
3 4 2 <08:17:10>
3 4 3 <2767824>
3 4 4 <vendor_20160201_67369072 - cb.mp3>
---
4 4 1 <2016-02-03>
4 4 2 <08:17:06>
4 4 3 <368928>
4 4 4 <vendor_20160201_67369072.mp3>
---

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM