After parsing the input line, awk provides access to the original line ($0
) as well as to each individual column ($1
, $2
, ...). While performing this process (lazily, on demand) - it knows exactly the position of the character where the 2nd column starts.
- Does it provide access to this info (i.e., at what position in the original line $0 does the 2nd column start)?
- If not - is there any sane/elegant way of finding it out properly? (I'm about to start coding an ugly and inefficient way of mimicking awk's internal behavior by using dynamic-regexps based on
FS
, handling specialFS==" "
case, using capturing groups, etc. But wanted your advice before I dive deep into it.)
Example 1 (default FS):
$ echo -n -e " \tFirst \t\t Second \t Third \t"\
|awk -F" " '{print "FS:["FS"]";for(i=0;i<=5;i++)if(""!=$i)print "$"i":["$i"]"}'\
|sed 's/\t/\\t/g'
FS:[ ]
$0:[ \tFirst \t\t Second \t Third \t]
$1:[First]
$2:[Second]
$3:[Third]
in here - I need to know that the 2nd column (Second
) starts with the letter S
and this is the 13th character in the input line (so I would be able to store First
as the key, and preserve/store the Second \t Third \t
intact as the value for the further use)
Example 2 (TAB as FS):
$ echo -n -e " \tFirst \t\t Second \t Third \t"\
|awk -F"\t" '{print "FS:["FS"]";for(i=0;i<=5;i++)if(""!=$i)print "$"i":["$i"]"}'\
|sed 's/\t/\\t/g'
FS:[\t]
$0:[ \tFirst \t\t Second \t Third \t]
$1:[ ]
$2:[First ]
$4:[ Second ]
$5:[ Third ]
in here - I need to know that the 2nd column (First
) starts with the letter F
and this is the 3rd character in the input line - so I would be able to store
(space) as the key, and preserve/store First \t\t Second \t Third \t
intact as the value for the further use
Example 3 (custom FS):
$ echo -n -e " \tFirst \t\t Second \t Third \t"\
|awk -F"[ \t]+" '{print "FS:["FS"]";for(i=0;i<=5;i++)if(""!=$i)print "$"i":["$i"]"}'\
|sed 's/\t/\\t/g'
FS:[[ \t]+]
$0:[ \tFirst \t\t Second \t Third \t]
$2:[First]
$3:[Second]
$4:[Third]
in here - I need to know that the 2nd column (First
) starts with the letter F
and this is the 3rd character in the input line - so I would know the 1st column is an empty string, and store the First \t\t Second \t Third \t
as the value for the further use
Example 4 (complex FS):
$ echo "-11...22;,;..;33-44...;"\
|awk -F"[^0-9-]+" '{print "FS:["FS"]";for(i=0;i<=5;i++)if(""!=$i)print "$"i":["$i"]"}'
FS:[[^0-9-]+]
$0:[-11...22;,;..;33-44...;]
$1:[-11]
$2:[22]
$3:[33-44]
in here - I need to know that the 2nd column (22
) starts with the character 2
and this is the 7th character in the input line - so I would be able to store -11
as the key, and 22;,;..;33-44...;
as the value for the further use
Basically the idea is to grab some (1st) columns for a custom use and to preserve (store into a variable) the remainder of the line (from 2nd column till end of line) intact.