【问题标题】:Comparing a variable with 2nd column if a file and printing the required output如果文件比较变量与第二列并打印所需的输出
【发布时间】:2021-09-04 17:39:00
【问题描述】:

我有一个查询生成的结果文件。该文件有 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

【问题讨论】:

    标签: linux shell unix scripting


    【解决方案1】:
    #!/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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-10
      • 2014-07-18
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2021-06-26
      • 2019-12-13
      • 1970-01-01
      相关资源
      最近更新 更多