Home > Software engineering >  Linux shell passing column position dynamically
Linux shell passing column position dynamically

Time:12-28

question is: how to pass column position (e.g., $2) dynamically through a loop.
Example file temp1

a 1 2  
a 2 3  
b 1 1  
b 3 2  
c 1 5   
c 2 6  

code so far (does not work :-))

#!/bin/bash
twopq () {

awk -v c1="$1" -v c2="$2" '{ if ($1==c1 && c2 == 1) {print}}' temp1 > temp2 

}
twopq a $2
twopq b $3  

Desired output in temp2 from 1st loop (1st col = 'a' and 2nd col = 1)
a 1 2

desired output in temp2 from 2nd loop (1st col= b and 3rd col = 1)
b 1 1

my pb is to pass the "$" through my loop to tell I'm looking for col2 in the first loop and col3 in the second loop

thanks for the help!

CodePudding user response:

Assumptions:

  • 1st argument is a value we're looking for in the 1st column of the input file
  • 2nd argument is the column number we're looking for that has a value of 1
  • print all lines that match the search criteria

Adding a couple lines to demonstrate multiple matches:

$ cat temp1
a 1 2
a 2 3
b 1 1
b 3 2
c 1 5
c 2 6
d 1 5                 # new line
d 1 9                 # new line

A few tweaks to OP's current code:

twopq () { awk -v val="$1" -v colnum="$2" '$1==val && $(colnum)==1' temp1; }

Taking for a test drive:

$ twopq a 2
a 1 2

$ twopq b 3
b 1 1

$ twopq d 2
d 1 5
d 1 9

NOTES:

  • once the output is verified OP can update the function as needed to capture the output to temp2 (eg, > temp2 to overwrite on each function call; >> temp2 to append with each function call)
  • alternatively, route the output from the function call to the output file (eg, twopq a 2 > temp2, twopq b 3 >> temp2)

CodePudding user response:

Like this:

#!/bin/bash

twopq () {    
    awk -v c1="$1" '($1==c1) {
        for (i=2; i<=NF; i  )
        if ($i == 1) {print;exit}
    }' temp1 | tee -a temp2 

}
twopq a 2
twopq b 3  

Output

a 1 2  
b 1 1 

CodePudding user response:

did you tried to use $c2 inside if condition ?

awk -v c1="$1" -v c2="$2" '{ if ($1==c1 && $c2 == 1) {print}}' temp1 > temp2
  • Related