Using AWK to take a range of columns and print them as a single column

StackOverflow https://stackoverflow.com/questions/23644184

  •  22-07-2023
  •  | 
  •  

سؤال

I have a file where I want to print every entry for a column i>N followed by the contents of the next column. Each line has the same number of columns. An example input:

a b c d 
a1 b1 c1 d1 
a2 b2 c2 d2 
a3 b3 c3 d3 

say in this case I want to skip the first column so the desired output would be

 b
 b1
 b2
 b3
 c
 c1
 c2
 c3
 d
 d1
 d2
 d3

I got close to what I wanted using

awk '{for(i=2; i<=NF; print $i; i++)}'

but this prints each entry in a line consecutively instead off all entries from each column consecutively.

Thanks in advance

هل كانت مفيدة؟

المحلول

If every line has same number of fields then you can do:

awk '
{
    for(i=2;i<=NF;i++) 
        rec[i]=(rec[i]?rec[i]RS$i:$i)
}
END {
    for(i=2;i<=NF;i++) print rec[i]
}' file 

If the number of fields are uneven, then you need to remember which line has the maximum number of fields.

awk '
{
    for(i=2;i<=NF;i++) {
        rec[i]=(rec[i]?rec[i]RS$i:$i)
    }
    num=(num>NF?num:NF)
}
END {
    for(i=2;i<=num;i++) print rec[i]
}' file

Output:

b
b1
b2
b3
c
c1
c2
c3
d
d1
d2
d3

نصائح أخرى

Using cut would be easier here:

# figure out how many fields
read -a fields < <(sed 1q file)
nf=${#fields[@]}

# start dumping the columns.
n=3
for ((i = n; i <= nf; i++)); do
    cut -d " " -f $i file
done
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top