Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cut command --complement flag equivalent in AWK

Tags:

unix

awk

I am new to writing shell scripts

I am trying to write an AWK command which does exactly the below

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

$IGNORE_RANGE can be of any value say, 1-5 or 5-10 etc

i cannot use cut since i am in AIX and AIX does not support --complement, is there any way to achieve this using AWK command

Example:

file.txt

abcdef
123456

Output

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
like image 345
Rasmi Avatar asked Sep 14 '26 09:09

Rasmi


2 Answers

Could you please try following, written and tested with shown samples. We have range variable of awk which should be in start_of_position-end_of_position and we could pass it as per need.

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

OR to make it more clear in understanding wise try following:

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

Explanation: Adding detailed explanation for above.

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.
like image 100
RavinderSingh13 Avatar answered Sep 18 '26 00:09

RavinderSingh13


You can do this in awk:

awk -v st=1 -v en=2 '{print substr($0, 1, st-1) substr($0, en+1)}' file
cdef
3456

Or:

awk -v st=4 -v en=5 '{print substr($0, 1, st-1) substr($0, en+1)}' file
abcf
1236
like image 24
anubhava Avatar answered Sep 18 '26 00:09

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!