1

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
}


"$@"
Jack
  • 23
  • 1
  • 4
  • Replace quotes by double quotes! See [Difference between single and double quotes in Bash](https://stackoverflow.com/q/6697753/1765658) – F. Hauri - Give Up GitHub Jun 23 '23 at 17:18
  • [shellcheck.net](https://www.shellcheck.net) wouold've pointed out several of the problems here; I recommend running your scripts past it and fixing what it points out. – Gordon Davisson Jun 23 '23 at 18:52

1 Answers1

0
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
Verpous
  • 588
  • 3
  • 7