linux - 如果文件比较变量与第二列并打印所需的输出
问题描述
我有一个从查询中生成的结果文件。该文件有 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
解决方案
#!/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
推荐阅读
- azure - 如何为具有相同标签集的不同文档布局训练自定义模型?
- r - 为什么我会收到警告“在 edit.data.frame(x) 中:在 'name' 中添加了因子级别”使用 edit(x)
- java - 数组错误在给定条件下有多少奇数和偶数
- python - 如何将数组([1,1,1])与数组([2,3,4])相乘以获得数组[[2,3,4],[2,3,4],[2,3,4] ]]?
- csv - backtrader 如何使用分析器访问数据?
- .net-core - 如何验证使用密钥提交的凭据以在 .net 核心中使用 google 登录?
- sql-server - 来自多个表的条件计数?
- java - 是否可以在 Android 中使用共享首选项保存多个 Pdf 文件的最后查看页码?
- python - 将 elasticsearch 快照保存在 s3 的文件夹中
- r - r中“!TRUE + TRUE”的奇怪结果