我做了一个小测试来回显我名为 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)