在awk命令中删除列

时间:2017-03-06 08:08:20

标签: unix awk split

我想删除列,因为现在我有一个命令,包括拆分,标题和预告片在一个命令中。我想在一个命令中执行拆分,标题,预告片和删除前3列

我的原始输出是

  Country   Gender    Plate       Name        Account Number        Car Name
    X        F          A          Fara        XXXXXXXXXX            Ixora
    X        F          b          Jiha        XXXXXXXXXX            Saga
    X        M          c          Jiji        XXXXXXXXXX            Proton

我的分割文件:

第一个文件

06032017

  Country   Gender    Plate       Name    Account Number     Car Name        
    X        F          A     Fara        XXXXXXXXXX         Ixora

EOF 1

第二档
06032017

  Country   Gender    Plate       Name        Account Number        Car Name
    X        F          b          Jiha        XXXXXXXXXX            Saga

EOF1

我的desitre输出:

06032017

    Name    Account Number     Car Name        
    Fara        XXXXXXXXXX         Ixora

EOF 1

06032017

  Name        Account Number        Car Name
  Jiha        XXXXXXXXXX            Saga

EOF1

这是我的拆分命令:

awk -v date="$(date +"%d%m%Y")" -F\| 'NR==1 {h=$0; next} 
{file="CAR_V1_"$1"_"$2"_"date".csv"; print (a[file]++?"": "DETAIL "date"" ORS h ORS) $0 > file}
END{for(file in a) print "EOF " a[file] > file}' HIRE_PURCHASE_testing.csv

1 个答案:

答案 0 :(得分:1)

想要了解如何跳过某些字段:

$ echo "Field1 Field2 Field3 Field4 Field5 Field6"  |awk '{print $0}'
Field1 Field2 Field3 Field4 Field5 Field6  #No skipping here. Printed just for comparison

$ echo "Field1 Field2 Field3 Field4 Field5 Field6"  |awk '{print substr($0, index($0,$4))}'
Field4 Field5 Field6

$ echo "Field1 Field2 Field3 Field4 Field5 Field6"  |awk '{$1=$2=$3="";print}'
   Field4 Field5 Field6
#Mind the gaps in the beginning. You can use this if you need to "delete" particular columns.
#Actually you are not really delete columns but replace their contents with a blank value.

$ echo "Field1 Field2 Field3 Field4 Field5 Field6"  |awk '{gsub($1FS$2FS$3FS$4,$4);print}'
Field4 Field5 Field6   #Columns 1-2-3-4 have been replaced by column4. No gaps here.

$ echo "Field1 Field2 Field3 Field4 Field5 Field6"  |awk '{print $4,$5,$6}' 
Field4 Field5 Field6
# If you have a fixed number of fields (i.e 6 fields) you can just do not print the first three fields and print the last three fields

改编自您现有的代码,

print (a[file]++?"": "DETAIL "date"" ORS h ORS) $0 > file

如果更改为

print (a[file]++?"": "DETAIL "date"" ORS h ORS) substr($0, index($0,$4)) > file

print (a[file]++?"": "DETAIL "date"" ORS h ORS) $4,$5,$6 > file #if you have a fixed number of columns in the file)

应该足够了。

下次您需要帮助时我会建议,简化问题以便更轻松地获得帮助。对于其他用户来说,很难完全跟随你。

另请查看此处了解所有这些功能的详细信息:https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html