在 awk 命令上传递脚本参数

0 bash awk shell-script arguments

我有一个管道分隔的文件,我需要 grep 第一列,如果模式匹配,我将打印整行。下面的命令正在运行,但是当我将它放在脚本上时,我认为$1它与命令冲突:

命令:

awk -F'|' < filename '{if ($1 == "stringtomatch") print $0}'
Run Code Online (Sandbox Code Playgroud)

脚本:

./scripts.sh stringtomatch
Run Code Online (Sandbox Code Playgroud)

脚本中的命令:

awk -F'|' < filename '{if ($1 == "$1") print $0}'
Run Code Online (Sandbox Code Playgroud)

$1包围在双引号是传递给脚本的参数。任何建议如何使这项工作?

ter*_*don 5

请注意,您可以大大简化您的awk. 如果表达式计算结果为,true则默认操作是打印当前行。所以这做同样的事情:

awk -F'|' < filename '$1 == "string"'
Run Code Online (Sandbox Code Playgroud)

无论如何,您可以使用-v选项来传递变量。所以你的脚本可以是:

#/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"
Run Code Online (Sandbox Code Playgroud)