![如何在 awk 打印中用 echo 分隔两个变量?](https://linux22.com/image/922249/%E5%A6%82%E4%BD%95%E5%9C%A8%20awk%20%E6%89%93%E5%8D%B0%E4%B8%AD%E7%94%A8%20echo%20%E5%88%86%E9%9A%94%E4%B8%A4%E4%B8%AA%E5%8F%98%E9%87%8F%EF%BC%9F.png)
我做了一个小测试来回显我名为 portal 的 .txt 文件中的所有内容。在终端中写入时,我希望脚本回显输入名称的所有内容,但我只显示第一个变量。
input=$1
for portal in $(grep $input /etc/portals | sed '/^#/ d' | awk '{print $1, $2}');
do
echo -e "\e[1;32m "$portal" \e[0m";
exit 0
done
else
echo -e "\e[1;31m --> Wrong Input <-- \e[0m"
exit 1
done
fi
=============
代码有效,但只打印了 $1,而不是 $2。如果我将代码更改为:awk '{print $1 $2}',则输出为 $1$2,变量之间没有制表符或空格。==================================
我怎样才能分离变量以便显示回声:
测试1 [制表符/空格] 测试2
答案1
#!/bin/bash
# exit if input is empty.
[[ -z $1 ]] && exit 1
# Check in the file /etc/portals for
# the existens of the word "$1" and place
# first word in "$a" and rest in "$b".
while read -r a b; do
printf %s\\t%s\\n $a "$b"
done < <(grep -P "^(?!#).*$1" /etc/portals)