linux - 使用 AWK 删除与 2 个模式匹配的列
问题描述
具有 ISBN、TITLE、OBSERVATION 和其他具有 OBSERVATION、TITLE、ISBN 的书籍的多个列表,我想删除 OBSERVATION 列,将 TITLE 打印为第 1 列,将 ISBN 打印为第 2 列,如下所示。
输入:
- 123654 宇宙学更新
- 35647 药物修订
- 987456 法学修订
- 更新修辞 123456
- 修订后的认识论 654321
所需输出:
- 宇宙123654
- 药 35647
- 修辞 123456
- 认识论 654321
我尝试了在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
解决方案
编辑:由于 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.
推荐阅读
- ios - 如何使用swift在ios的firebase firestore中的文档中获取arrayList
- c - C 正式定义中的命名空间
- javascript - 数据从数据库到 laravel 中的 fusioncharts
- python - GCP DataflowRunner 导入错误
- postgresql - 使用正则表达式从字符串列中提取开始和结束日期的函数
- ionic-framework - ionic4 在 ios 上制作片段,使其看起来像在带有 css 的 android 上
- python-3.x - 如何分解嵌套列表?
- python - 在 Python 中没有 pandas 的旋转?
- php - 为什么这个 php 脚本总是显示“kiriman gagal diterima”(接收失败)?
- android - 如何在移动应用程序的sails.js中从以前的设备注销用户?