如何将shell变量传递给shell脚本中的awk命令

时间:2021-09-24 19:24:45

I just want to pass a shell variable that stores name of a file to awk command. When I searched this problem on the net I see many different options but none of them worked for me. I tried the followings:

我只想传递一个存储文件名的shell变量到awk命令。当我在网上搜索这个问题时,我看到了许多不同的选项,但它们都没有为我工作。我尝试了以下几点:

#!/bin/bash
for i in "$@"
do
case $i in
    -p=*|--producedfile=*)
    PFILE="${i#*=}"
    shift # past argument=value
    *)
          # unknown option
    ;;
esac
done
echo "PRODUCEDFILE  = ${PFILE}"
awk  -v FILE=${PFILE} '{print FILE $0}' #DIDNT WORK
awk   '{print FILE $0}' ${PFILE} # DIDNT WORK
awk  -v FILE=${PFILE} '{print $0}' FILE #DIDNT WORK

1 个解决方案

#1


2  

To pass a shell variable to awk, you correctly used -v option.

要将shell变量传递给awk,请正确使用-v选项。

However, the shift was unnecessary (you're iterating options with for), ;; was missing (you have to terminate each case branch), as well as was the name of the file for awk to process. Fixed, your script looks like:

但是,转换是不必要的(你用for迭代选项),;;缺少(您必须终止每个案例分支),以及要处理的awk文件的名称。修复了,您的脚本如下所示:

#!/bin/bash
for i in "$@"; do
    case $i in
        -p=*|--producedfile=*)
            PFILE="${i#*=}"
            ;;
        *)
             # unknown option
            ;;
    esac
done

echo "PRODUCEDFILE = ${PFILE}"
awk  -v FILE="${PFILE}" '{print FILE, $0}' "${PFILE}"

Note however, awk already makes the name of the currently processed file available in the FILENAME variable. So, you could also write the last line as:

但请注意,awk已在FILENAME变量中提供当前处理文件的名称。所以,你也可以把最后一行写成:

awk '{print FILENAME, $0}' "${PFILE}"

#1


2  

To pass a shell variable to awk, you correctly used -v option.

要将shell变量传递给awk,请正确使用-v选项。

However, the shift was unnecessary (you're iterating options with for), ;; was missing (you have to terminate each case branch), as well as was the name of the file for awk to process. Fixed, your script looks like:

但是,转换是不必要的(你用for迭代选项),;;缺少(您必须终止每个案例分支),以及要处理的awk文件的名称。修复了,您的脚本如下所示:

#!/bin/bash
for i in "$@"; do
    case $i in
        -p=*|--producedfile=*)
            PFILE="${i#*=}"
            ;;
        *)
             # unknown option
            ;;
    esac
done

echo "PRODUCEDFILE = ${PFILE}"
awk  -v FILE="${PFILE}" '{print FILE, $0}' "${PFILE}"

Note however, awk already makes the name of the currently processed file available in the FILENAME variable. So, you could also write the last line as:

但请注意,awk已在FILENAME变量中提供当前处理文件的名称。所以,你也可以把最后一行写成:

awk '{print FILENAME, $0}' "${PFILE}"