首页 > 解决方案 > cut command --complement flag 在 AWK 中等效于复杂参数

问题描述

这个问题是对现有问题的跟进

不要将此标记为重复,因为问题的期望完全不同

我正在尝试编写一个完全执行以下操作的 AWK 命令

命令 1:

cut --complement -c $IGNORE_RANGE file.txt > tmp

命令 2:

cut --complement -d, -f$IGNORE_RANGE $report  > tmp

$IGNORE_RANGE 可以是任何值,例如 1-5,6 或 1,3,5 1,3-5 等

我不能使用 cut,因为我在 AIX 中并且 AIX 不支持 --complement,有没有办法使用 AWK 命令来实现这一点

命令 1 的示例:

文件.txt

abcdefg
1234567

输出

cut --complement -c 1-5,6 file.txt > tmp
g
7


cut --complement -c 1,3,5 file.txt > tmp
bdfg
2467

cut --complement -c 1,3-5 file.txt > tmp
bfg
267

命令 2 的示例:

文件.txt

data1,data2,data3,data4,data5,data6,data7

输出

cut --complement -d, -f 1-5,6 file.txt > tmp
data7

cut --complement -d, -f 1,3,5 file.txt > tmp
data2,data4,data6,data7

cut --complement -d, -f 1,3-5 file.txt > tmp
data2,data6,data7

标签: unixawkcut

解决方案


1st solution for OP's position number problem: Could you please try following, a generic solution based on provided samples written and tested in GNU awk and needed GNU awk to be executed. One could give ranges or individual position number separated by , in awk's ignore_pos variable.

awk -v FS= -v ignore_pos="1-5,6" '
BEGIN{
  num=split(ignore_pos,array1,",")
  for(i=1;i<=num;i++){
    if(array1[i]~/-/){
       split(array1[i],array2,"-")
       for(j=array2[1];j<=array2[2];j++){
         ignore[j]
       }
    }
    else{
       ignore[array1[i]]
    }
  }
}
{
  for(i=1;i<=NF;i++){
    if(!(i in ignore)){ val=val $i }
  }
  $0=val
  val=""
}
1
'  Input_file


2nd solution for OP's field number problem: When one wants to ignore fields we could use this solution then(OP's command2 examples taken here to run this). As per OP's samples ,comma has been made as field separator for Input_file here.

awk -v ignore_field="1-5,6" '
BEGIN{
  FS=OFS=","
  num=split(ignore_pos,array1,",")
  for(i=1;i<=num;i++){
    if(array1[i]~/-/){
      split(array1[i],array2,"-")
      for(j=array2[1];j<=array2[2];j++){
        ignoreFields[j]
      }
    }
    else{
      ignoreFields[array1[i]]
    }
  }
}
{
  for(i=1;i<=NF;i++){
    val=""
    if(!(i in ignoreFields)){  val=(val?val OFS:"")$i  }
  }
  $0=val
}
1
' Input_file

推荐阅读