0

I have a file, script.sh, like this:

#!/bin/bash

awk -F@ '{ print $1 } file.csv

This prints column 1 of file.csv.

I'd like to be able to run script.sh with an argument such as ./script.sh 3 which means it will instead print column 3. Or ./script.sh 10, which means it will instead print column 10.

How can I can the command line argument to AWK in this way?

Village
  • 22,513
  • 46
  • 122
  • 163

2 Answers2

2

You could try with:

awk -v i=$1 -F@ '{print $i}' file.csv
Joaquin
  • 2,013
  • 3
  • 14
  • 26
1

Could you please try following.(have added usage in script too in case a user doesn't pass it, user should get message for it)

cat script.sh
#!/bin/bash
val="$1"
if [[ -n "$val" ]]
then
    awk -v value="$val" -F'@' '{print $value}' file.csv
else
    echo "Usage: Please pass an argument to print a specific field of line while running script as ./script.sh 1"
fi
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93