Extract values from a specific column to the end

Hello friends,

I have a text file with many columns (no. columns vary from row to row) separated by space. I need to collect all the values from 18th column to the end from each line and group them as pairs and then numbering like below..

  1. 18th-col-value 19th-col-value 2. 20th-col-value 21st-col-value 3. 22nd-col-value 23rd-col-value 4.....
  2. 18th-col-value 19th-col-value 2. 20th-col-value 21st-col-value 3. 22nd-col-value 23rd-col-value 4.....
  3. 18th-col-value 19th-col-value 2. 20th-col-value 21st-col-value 3. 22nd-col-value 23rd-col-value 4.....
    ......
    ......
    ........

Please advise!

Thanks a lot!!

Since you've been following this forum for several years and have posted well over 150 messages, please show us what you've tried so far to convert the input you have to the format you want.

Thanks Don for the reply!

I think my requirement is related with sed/awk which are always mysterious to me.

My initial requirement was to extract only 4 fields from 18th col so I could manage it by looping every line

cat filename | while read line

and hardcoded them using

echo 1. awk  '{print $18 $19}' "${line}" 2. awk  '{print $20 $21}' "${line}"

but now we have to extract till the end (probably we need something like a loop with awk using "$").

I wrote big script and am stuck up with extracting part. Please advise!

Assuming that your input file line lengths don't exceed LINE_MAX limits on your system, the following seems to do what you want:

awk '{  for(i = 18; i <= NF; i += 2)
                printf("%s%d. %s %s", i == 18 ? "" : " ",
                        (i - 16) / 2, $i, $(i + 1))
        printf("\n");
}' file

If you want to run this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

PS Is there anything in this script you don't understand?

1 Like

Fantastic, Thanks Don! Worked like charm!!

How could you offer the solution so quickly? Please suggest how can I easily learn about awk and sed? :slight_smile:

Given your problem statement (with the restrictions I stated in my response), it just seemed obvious to me how to do it.

Look at examples posted here in The UNIX and Linux Forums and figure out what the scripts do. If you can't figure out how they work, ask questions.