Search code examples
linuxbashshellsh

How to pass the column number as a parameter in shell function


I am new with Lunix, I tried to write a function, which takes 3 parameters input data, output data, and selected column

The function: read the input data, write and remove duplicated row for the selected column and save it output data.

If I do on command like that, it worked


cat new_trans.txt | awk -F',' '\!seen[$1]++ { print $1}' > test

bash ./shell_fn.sh testA new_trans.txt test_new_trans.txt $1

testA() {
  col = $3
  cat $1 | awk -F',' '\!seen[\$$col]++ { print \$$col}' > $2
  cat $2 | head
}


"$@"

Solution

  • testA() {
      col="$3"
      awk -F ',' -v c="$col" '!seen[$c]++ { print $c }' "$1" > "$2"
      head "$2"
    }
    

    Things I changed:

    1. No spaces in the col assignment, those are not allowed
    2. Instead of piping from cat, you can just pass the filename to these commands directly
    3. Since we're using single quotes ', backslashes were unnecessary
    4. Quoting variables to avoid problems if they have spaces in them
    5. Declaring a variable c that lives inside the awk script and equals col