找到完全匹配时,awk会打印确切的字段

时间:2017-10-08 07:37:30

标签: bash awk

我有一个包含信息的persons.dat文件。

这是一个示例行。

1129|Lepland|Carmen|female|1984-02-18|228T04:39:58.781+0000|81.25.252.111|Internet Explorer

1129是身份证。

我被要求根据他们的身份证明显示任何人的信息,特别是他们的名字(Carmen),(Lastname = Lepland)和出生日期(1984-02-18)以空格分隔。

我已将id存储在shell变量IDNumber中,如下所示:

for arg1 in $@;do # Retrieve ID Number
if  [ $1 = "-id" ];then
        IDNumber="$2"
fi
shift
done

如何使用awk显示一个ID的确切字段?

1 个答案:

答案 0 :(得分:1)

The command line argument parsing of the shell script is a bit confusing like that, since arg1 is not used. And even after it finds -id and assigns $2 to IDNumber, the iteration continues. For example when the arguments are -id 3, after IDNumber=3, the iteration continues, checking if [ 3 = "-id" ]. Also, the "$1" in if [ $1 = ... ] should be double-quoted, otherwise the script will crash if there is an empty argument.

Here's one way to fix these issues:

while [ $# -gt 0 ]; do
    if [ "$1" = -id ]; then
        id=$2
    fi
    shift
done

Then you can use id with Awk like this:

awk -F'|' -v id="$id" '$1 == id {print $3, $2, $5}' persons.dat

That is:

  • Set | as the field separator
  • Set id variable in Awk to the value of $id in the shell
  • Find the record in the input where the first field ($1) is equal to id
  • Print the columns you need