We have a sample data as below


I have used below code to split the data as below

awk -F\| '
BEGIN { print "EMP_ID|Values|HeaderName" }
NR==1 { for(i=3;i<=NF;i++) h[i]=$i }
NR>1 { for(i=3;i<=NF;i++) print $1"|"$2"|"$i"|"h[i] }
' records.txt 

And Output IS


In the command i have specified """ print $1"|"$2"|"$i"|"h[i] """ , Starting first and second column appending with $i and h[i]. Instead of Specifying $1,$2 i have some more columns which results in mentioning as $1"|"$2"|"$3"|"$4 ....

Instead of keeping all the column names sequentially , can i mention any range. I have tried below command but didn't worked.

for i in ${@:1:4}

Instead of keeping $1"|"$2"|"$3"|"$4..... can i specify any range like 1:4


You can print data from a range of columns with a construct like this :

echo {0..9} | awk '{ for(i=3;i<8;i++) {printf $i"|"} }'

outputs :

  • i am unable to get the output. It shows blank values from 2nd record. As per the above output for all the four records first 2 columns should remain same , but here i am getting blanks from 2nd record. – Arya May 20 at 13:54
$ awk -F'|' '
    BEGIN {
      getline; split($0,a); OFS=FS; 
      print "EMP_ID", "EMP_NAME", "Values", "HeaderName"
      for (i=3;i<=NF;i++) print $1, $2, $i, a[i];
' sample

If you want to limit the range of output fields to be the same as the number of header fields, change split($0,a) to n = split($0,a) and then change the for loop termination condition to i<=n instead of i<=NF. Or change it to a fixed number if that's what you want.

  • Hi , Thanks for the reply. Instead of print $1, $2 .... Instead if $1 , $2 can i specify any range , because i have many columns to mention it like $1,$2,$3,$4 .... -- i want to overcome this and mention any range. Do we have any possibility ? – Arya May 20 at 14:59
  • @Arya please see my edit – steeldriver May 20 at 15:00
  • Sorry for repeating the same. I am trying to achieve the condition as below.. instead of " for (i=3;i<=NF;i++) print $1, $2, $i, a[i]; " , can i specify it like " for (i=3;i<=NF;i++) print $1:2 , $i, a[i]; – Arya May 20 at 15:03
  • @Arya AFAIK awk does not have such an "array slice" syntax – steeldriver May 20 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.