首页 > 解决方案 > 使用 AWK 删除与 2 个模式匹配的列

问题描述

具有 ISBN、TITLE、OBSERVATION 和其他具有 OBSERVATION、TITLE、ISBN 的书籍的多个列表,我想删除 OBSERVATION 列,将 TITLE 打印为第 1 列,将 ISBN 打印为第 2 列,如下所示。

输入:

所需输出:

我尝试了在SE中找到的这段代码并操作了几个小时而没有结果

awk -v OFS='\t' 'NR==1{for (i=1;i<=NF;i++)if ($i=="Updated"){n=i-1;m=NF-(i==NF)}} {for(i=1;i<=NF;i+=1+(i==n))printf "%s%s",$i,i==m?ORS:OFS}' file  

标签: linuxshellawksh

解决方案


编辑:由于 OP 在评论中确认 Input_file 不是逗号分隔的,然后通过查看 OP 的尝试,请您尝试以下操作。

awk '{if($1~/^[0-9]+/){print $2,$1} else {print $2,$3}}' Input_file

说明:为上述代码添加说明。

awk '                   ##Starting awk program from here.
{
  if($1~/^[0-9]+/){     ##Checking if condition if a line starts with digit then do following.
    print $2,$1         ##Printing 2nd field and then 1st field of line here.
  }
  else{                 ##Using else in case that above if condition is NOT TRUE then do following.
    print $2,$3         ##Printing 2nd and 3rd field of line.
  }
}
' Input_file            ##Mentioning Input_file name here, which awk is processing.


以下解决方案认为 OP 的 Input_file 是 csv 和逗号分隔的。

看起来您的 Input_file 是逗号分隔的,您想打印空格分隔的第二列的第一个字段和行的第一个字段。如果是这种情况,请尝试以下操作。

awk '
BEGIN{
  FS=OFS=","
}
{
  split($2,array," ")
  print array[1] $1
}
' Input_file

说明:为上述代码添加详细说明。

awk '                      ##Starting awk program from here.
BEGIN{                     ##Starting BEGIN section from here.
  FS=OFS=","               ##Setting comma for FS and OFS here for all lines of Input_file.
}
{                          ##Starting main BLOCK from here for this program.
  split($2,array," ")      ##Splitting 2nd field to array named array whose delimiter is space.
  print array[1] $1        ##Printing array 1st element and 1st field of current line.
}
' Input_file               ##Mentioning Input_file name here.


如果您的完整 Input_file 以逗号分隔,那么您不仅需要打印如下字段。

awk '
BEGIN{
  FS=OFS=","
}
{
  print $2,$1
}
' Input_file

说明:为上述代码添加说明。

awk '             ##Starting awk program from here.
BEGIN{            ##Starting BEGIN section from here.
  FS=OFS=","      ##Setting comma for FS and OFS here for all lines of Input_file.
}
{
  print $2,$1     ##Printing each line 2nd field and 1st field.
}
' Input_file      ##Mentioning Input_file name here.

推荐阅读