1

I'm looking to conditionally select two columns from the third line of a file based on the first column of the first line of the file.

Here is the file format:

v1
shortdesc
value1 value2 value3 value4 ...

Using this example, I'd want value2 and value3 if v1, otherwise, I'd like value1 and value4.

I know how to get the line and column using something like awk 'FNR ==1 {print $1} but how do I use the if clause?

The code that is not working for me looks something like this:

awk '{if("NR == 1 $1"=="v1") {FNR==3 print $2 "\t" $3;} else {FNR==3 print $1 "\t" $4;}}'
2

You can try this one:

awk 'NR == 1 { if ($1 == "v1") { p = 1; } } NR == 3 { if (p) { print $2 "\t" $3; } else { print $1 "\t" $4; } }' file
  • awk 'NR==1{a=$1}NR==3{if(a=="v1")print $2,$3;else print $1,$4;exit}' OFS='\t' file – Costas May 20 '15 at 20:18
  • @Costas post it as answer. – taliezin May 20 '15 at 20:22
  • 1
    it is just variant of yours with some extra {} removed – Costas May 20 '15 at 20:23
1

Just for fun:
sed

sed -n '1h
        3{
            x
            G
            s/v1\n\S* \(\S* \S*\).*/\1/p
            t
            s/.*\n\(\S*\) \S* \S*\( \S*\).*/\1\2/p
          }
         4Q' file

test, head, tail, cut

[ $(head -1 file) == 'v1' ] &&
    field='2,3' ||
    field='1,4'
head -5 file | tail -1 | cut -d" " -f"$field"

bash

{ read v1
  read
  read a b c d e
  } <file
[ "$v1" == 'v1' ] && echo $b $c || echo $a $d

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.