cut 命令 --complement 等效于 AWK 的标志

Ras*_*smi 2 unix awk

我是编写 shell 脚本的新手

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

cut --complement -c $IGNORE_RANGE file.txt > tmp
Run Code Online (Sandbox Code Playgroud)

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

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

例子:

文件.txt

abcdef
123456
Run Code Online (Sandbox Code Playgroud)

输出

cut --complement -c 1-2 file.txt > tmp

cdef
3456


cut --complement -c 4-5 file.txt > tmp
abcf
1236

cut --complement -c 1-5 file.txt > tmp
f
6
Run Code Online (Sandbox Code Playgroud)

Rav*_*h13 6

您能否尝试使用所示示例进行以下,编写和测试。我们有range变量awk应该在里面start_of_position-end_of_position,我们可以根据需要传递它。

awk -v range="4-5" '
BEGIN{
  split(range,array,"-")
}
{
  print substr($0,1,array[1]-1) substr($0,array[2]+1)
}
' Input_file
Run Code Online (Sandbox Code Playgroud)

或者为了更清楚地理解,请尝试以下操作:

awk -v range="4-5" '
BEGIN{
  split(range,array,"-")
  start=array[1]
  end=array[2]
}
{
  print substr($0,1,start-1) substr($0,end+1)
}
'  Input_file
Run Code Online (Sandbox Code Playgroud)

说明:为以上添加详细说明。

awk -v range="4-5" '                                ##Starting awk program from here creating range variable which has range value of positions which we do not want to print in lines.
BEGIN{                                              ##Starting BEGIN section of this program from here.
  split(range,array,"-")                            ##Splitting range variable into array with delimiter of - here.
  start=array[1]                                    ##Assigning 1st element of array to start variable here.
  end=array[2]                                      ##Assigning 2nd element of array to end variable here.
}
{
  print substr($0,1,start-1) substr($0,end+1)       ##Printing sub-string of current line from 1 to till value of start-1 and then printing from end+1 which basically means will skip that range of characters which OP does not want to print.
}
'  Input_file                                       ##Mentioning Input_file name here.
Run Code Online (Sandbox Code Playgroud)

  • ++ 比我的更好的解决方案 (2认同)