Home > Software design >  Filter and sort columm
Filter and sort columm

Time:01-13

I learnt awk and sed, but I'm stuck at this problem, can anyone help me? I have a table like this:

a1 a2 a3 a4 
b1 b2 b3 b4
c1 c2 c3 c4

So I want to filter value at odd and even columns like this: table 1:

a1
a3
b1
b3
c1
c3

and table 2:

a2 
a4
b2
b4
c2
c4

How can I do this?

CodePudding user response:

It's easy to work in awk using:

awk '{ for (i = 1; i <= NF; i  = 2) print $i > "table.1"
       for (i = 2; i <= NF; i  = 2) print $i > "table.2" }' data

For each line, the first loop writes the odd fields to table.1 and the second loop writes the even fields to table.2. It will even work with different numbers of columns in each line if the input data is not wholly consistent. A single pass through the input data generates both output files.

CodePudding user response:

If you have the maximum number of fields (say, 100 ) just use cut:

$ echo 'a1 a2 a3 a4
b1 b2 b3 b4
c1 c2 c3 c4' | cut -d' ' -f $(seq -s, 2 2 100) | tr ' ' '\n'
a2
a4
b2
b4
c2
c4

and for the odd ones seq would just start at 1.

Here's the same thing in awk (i=1 for the odd ones):

echo ... | awk '{for(i=2; i<=NF;i =2){ print $i}}'
  • Related