![如何仅使用 awk 打印与同一用户相关的某一列的内容?](https://linux22.com/image/161694/%E5%A6%82%E4%BD%95%E4%BB%85%E4%BD%BF%E7%94%A8%20awk%20%E6%89%93%E5%8D%B0%E4%B8%8E%E5%90%8C%E4%B8%80%E7%94%A8%E6%88%B7%E7%9B%B8%E5%85%B3%E7%9A%84%E6%9F%90%E4%B8%80%E5%88%97%E7%9A%84%E5%86%85%E5%AE%B9%EF%BC%9F.png)
我有这样的专栏:
User ColumnA ColumnB ComumnC
abc123 hi hello howdy?
xyz123 Namaste que paso rowdy?
abc123 hi hello bowdy?
我想编写 gawk 脚本来打印第 3 列中与 abc123 相关的内容,如下所示:
User: abc123
howdy?
bowdy?
到目前为止我得到了这个:
gawk '/^[a-z]{3}[0-9]{3}/ {
temp=$1
printf ("User: %s\n", $1);
printf ("\t %s\n", $4)
}' $1
但它会在每一行中打印 C 列中的所有用户及其内容,而不像这样合并 C 列中相同用户的内容。
User: abc123
howdy?
User: xyz123
rowdy?
User: abc123
bowdy?
有什么建议么?
答案1
使用awk
:
awk -F'\t' '
NR>1{
if(!o[$1]) {o[$1]="User: "$1"\n\t"$4}
else {o[$1]=o[$1]"\n\t"$4}
}
END { for (i in o) print o[i] }
' file
输出:
User:abc123
howdy?
bowdy?
User:xyz123
howdy?
答案2
我们到了:
# Save the filename
filen="test.txt"
# Save the column name
col_name="$(head -n1 $filen|awk '{print $1}')"
# Save the target word
to_find="abc123"
echo "$col_name: $to_find" ; for name in $(grep $to_find $filen | awk '{print $4}'); do echo " $name"; done
文本示例:
User ColumnA ColumnB ComumnC
abc123 hi hello howdy?
xyz123 Namaste que paso rowdy?
abc123 hi hello bowdy?
输出:
User: abc123
howdy?
bowdy?