首页 > 解决方案 > 如果文件比较变量与第二列并打印所需的输出

问题描述

我有一个从查询中生成的结果文件。该文件有 2 列。第一个是名称,第二个是 id.. 现在我有一个 id 变量。我必须将此 id 变量与第二列中的值进行比较并打印输出如下。文件

sam,12
justin,12,
jarvis,14

现在的 $id = 12。输出应该如下

sam is having same id as main id $id
justin is having same id as main id $id
jarvis id does not matches with main id $id

我在下面尝试过,但没有产生所需的输出。有人可以指导我哪里做错了吗

#!/bin/bash
awk 'BEGIN {FS=","} 
{ if ($2 == $id) 
echo "$1 is having same id as main id $id "
else
echo  "$1 id does not matches with main id $id" ' > a.txt

标签: linuxshellunixscripting

解决方案


#!/bin/bash

awk -v id=$id  -F, '
    #"id" == variable $id, "-F," == split separator
    $2==id { print $1" is having same id as main id "$2; next }
    # if second field is equals to $id; then print "...", and skip next block
    { print $1" id does not matches with main id "$2 }' input.txt > output.txt
    # else user's id is not equals to $id; print "..."

输出:

$ cat input.txt
sam,12
justin,12,
jarvis,14
$ id=12; awk -v id=$id -F, '$2==id { print $1" is having same id as main id "$2; next } { print $1" id does not matches with main id "$2 }' input.txt > output.txt
$ cat output.txt
sam is having same id as main id 12
justin is having same id as main id 12
jarvis id does not matches with main id 14

推荐阅读