Search code examples
filebashshellunixsolaris

How to read specific line and specific position?


I have a problem reading a string in specific line and specific position. I have an input file that has a fixed position and fixed length for each value in every row. This is an example of my input file:

sltele     Hoodie   24051988 d12Hdq
sltele     Hoodie   07051987 d30Hdq
sltele     Hoodie   07082011 d08Hdq
sltele     Hoodie   09081961 d04Hdq
sltele     Hoodie   20041962 d14Hdq
sltele     Hoodie   20032000 d01Hdq
sltele     Hoodie   13062002 d05Hdq

I need to read a string in 3rd column in first line. So, I used this

awk 'NR==1 {print $2, $3}' inputfile.inp

How can I get an exact result with character position as parameter? (12nd-18th and 21st-28th)


Solution

  • use cut -c

    Check the man page for more details.

    also you can use the below:

    echo "abcdefghij" | awk '{print substr($0,2,2),substr($0,6,2)}'
    bc fg
    

    above is 2 characters from second position and 2 chars from 6th position.

    your solution will be :

    awk 'NR==1 {print substr($0,12,6),substr($0,21,7)}' inputfile.inp
    

    the above command will get the 6 chars from 12th position and 7 chars from 21st position in line number 1.