Search code examples
shellunixawkkshseparator

How extract a field from file with awk without separators in Unix


I've got a file calling "file" where there are some fields separated with a separator. The structure of the file is:

@field1@field2@field3@field4

With awk i've extracted the fields without separators.

vr=$file;

sep_mx=`echo $vr | awk '{
    n=split($0,x,"@");
    print n
}'` 
echo $sep_mx
## here the number of substring produced is calc.

while ((i<=$max)); 
do
    # would print individual substring one at a
    # time as the counter increases.
    echo $vr | awk -v er=$i '{
        n=split($0,x,"@"); print x[er]
    }'
    ((i+=1))
done

The output is:

field1
field2
field3
field4

If i want to extract only the second field from the code i've just posted how can i do it? Thanks


Solution

  • With bash:

    $ while IFS=@ read -r col1 col2 col3 col4; do 
          echo $col3
      done <<< '@field1@field2@field3@field4'
    field2
    

    Another way with awk

    $ awk '{split($0,ary,/@/); print ary[3]}' <<< '@field1@field2@field3@field4'
    field2