如何在awk中切割字段
How to cut field in awk
我想写脚本文件来切割字段然后用它来比较字段然后打印
例如:我的输入文件
ADC1/asf/sd/df_adc1/125125
AED1/asf/sd/df_aed1/asfk
ASQ2/asf/df_asq2/aks
ABX5/df_abx5/asf/sd/sdgqw
输出文件:最后一个字段将从头开始打印到与第一个字段相同但不大写的字段。我将比较第一个字段,然后找到单词并从开始打印到我比较过的单词。
ADC1/asf/sd/df_adc1/125125 ADC1 ADC1/asf/sd/df_adc1
AED1/asf/sd/sf_aed1/asfk AED1 AED1/asf/sd/sf_aed1
ASQ2/asf/dg_asq2/aks ASQ2 ASQ2/asf/dg_asq2
ABX5/da_abx5/asf/sd/sdgqw ABX5 ABX5/da_abx5
我曾使用 awk 拆分 :
awk '{split(,a,"/"); {print , a[1]}}' input > output
和那样的输出
ADC1/asf/sd/df_adc1/125125 ADC1
AED1/asf/sd/df_aed1/asfk AED1
ASQ2/asf/df_asq2/aks ASQ2
ABX5/df_abx5/asf/sd/sdgqw ABX5
但我不知道如何比较最后一个字段
使用您展示的示例,请尝试执行以下 awk
程序。
awk '
BEGIN{ FS=OFS="/" }
{
val=""
for(i=1;i<=NF;i++){
if(i>1 && index(tolower($i),tolower())){
print [=10=]" "" "val OFS $i
}
val=(val?val OFS:"")$i
}
}
' Input_file
说明:为上述解决方案添加详细说明。
awk ' ##Starting awk program from here.
BEGIN{ FS=OFS="/" } ##Setting FS and OFS as / here.
{
val="" ##Nullifying val here.
for(i=1;i<=NF;i++){ ##Traversing through all fields here.
if(i>1 && index(tolower($i),tolower())){ ##Checking if field is greater than 1 and is found in $i(current field) in case-insensitive mode then do following.
print [=11=]" "" "val OFS $i ##Printing current line first field val OFS and current field.
}
val=(val?val OFS:"")$i ##Creating val which has val and current field value in it.
}
}
' Input_file ##Mentioning Input_file name here.
我想写脚本文件来切割字段然后用它来比较字段然后打印 例如:我的输入文件
ADC1/asf/sd/df_adc1/125125
AED1/asf/sd/df_aed1/asfk
ASQ2/asf/df_asq2/aks
ABX5/df_abx5/asf/sd/sdgqw
输出文件:最后一个字段将从头开始打印到与第一个字段相同但不大写的字段。我将比较第一个字段,然后找到单词并从开始打印到我比较过的单词。
ADC1/asf/sd/df_adc1/125125 ADC1 ADC1/asf/sd/df_adc1
AED1/asf/sd/sf_aed1/asfk AED1 AED1/asf/sd/sf_aed1
ASQ2/asf/dg_asq2/aks ASQ2 ASQ2/asf/dg_asq2
ABX5/da_abx5/asf/sd/sdgqw ABX5 ABX5/da_abx5
我曾使用 awk 拆分 :
awk '{split(,a,"/"); {print , a[1]}}' input > output
和那样的输出
ADC1/asf/sd/df_adc1/125125 ADC1
AED1/asf/sd/df_aed1/asfk AED1
ASQ2/asf/df_asq2/aks ASQ2
ABX5/df_abx5/asf/sd/sdgqw ABX5
但我不知道如何比较最后一个字段
使用您展示的示例,请尝试执行以下 awk
程序。
awk '
BEGIN{ FS=OFS="/" }
{
val=""
for(i=1;i<=NF;i++){
if(i>1 && index(tolower($i),tolower())){
print [=10=]" "" "val OFS $i
}
val=(val?val OFS:"")$i
}
}
' Input_file
说明:为上述解决方案添加详细说明。
awk ' ##Starting awk program from here.
BEGIN{ FS=OFS="/" } ##Setting FS and OFS as / here.
{
val="" ##Nullifying val here.
for(i=1;i<=NF;i++){ ##Traversing through all fields here.
if(i>1 && index(tolower($i),tolower())){ ##Checking if field is greater than 1 and is found in $i(current field) in case-insensitive mode then do following.
print [=11=]" "" "val OFS $i ##Printing current line first field val OFS and current field.
}
val=(val?val OFS:"")$i ##Creating val which has val and current field value in it.
}
}
' Input_file ##Mentioning Input_file name here.