我有这样的专栏:
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?