0

I have a pipe-delimited file and I need to grep the first column and if a pattern matched, I will print the whole line. The command below is working but when I put it on a script, I think the $1 is conflicting the command:

Command:

awk -F'|' < filename '{if ($1 == "stringtomatch") print $0}'

Script:

./scripts.sh stringtomatch

Command in script:

awk -F'|' < filename '{if ($1 == "$1") print $0}'

The $1 enclosed in the double quotes is the argument passed to the script. Any advise how to make this work?

4

1 Answer 1

5

Note that you can greatly simplify your awk. The default action if an expression evaluates to true is to print the current line. So this does the same thing:

awk -F'|' < filename '$1 == "string"'

Anyway, you can use the -v option to pass a variable. So your script can be:

#/bin/sh

if [ $# -lt 1 ]; then
  echo "At least one argument is required"
  exit
fi

## Allow the script to get the filename from the 2nd argument, 
## default to 'filename' if no second argument is given
file=${2:-filename}

awk -F'|' -v str="$1" '$1 == str' "$file"
2
  • awk will also take the filename - to mean stdin. So making that declaration into file="${2:--}" will use stdin if no filename is supplied. There is a variant that will pass either a list of files or - from the command line, but you would need to shift $1 off first. Sep 25, 2020 at 9:20
  • @Paul_Pedant ooh, nice, thanks. I won't add it to the answer though since the OP was already hardcoding the file name, so I am assuming they prefer to have a file. Great trick for next time though!
    – terdon
    Sep 25, 2020 at 9:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .