[英]How to compare strings containing a square bracket in Bash
I am searching for a comparison with square brackes in bash. 我正在寻找bash中方括号的比较。
Situation: I have a hosts file that contains hostnames that looks like 情况:我有一个主机文件,其中包含看起来像这样的主机名
[debian]
ansible
host
names
[centos]
more
hosts
now I want to scan all host's ssh keys (first echo, later use ssh-keyscan): 现在我想扫描所有主机的ssh密钥(第一次回显,以后使用ssh-keyscan):
while read hostName
do
if [[ $hostName != "" ]] && [[ $hostName != "\[*" ]] ; then
echo $hostName
#ssh-keyscan $hostName
fi
done < hosts
while [[ $hostName != "" ]]
does it's job the part containing the comparison for square brackets [[ $hostName != "\\[*" ]]
does not. 而[[ $hostName != "" ]]
做到,包含方括号[[ $hostName != "\\[*" ]]
不起作用。 Atm the result looks like this: Atm的结果如下所示:
[debian]
ansible
host
names
[centos]
more
hosts
I want it to look like: 我希望它看起来像:
ansible
host
names
more
hosts
While eg How to compare strings in Bash covers the general topic, it does not cover my question. 例如, 如何在Bash中比较字符串涵盖了一般主题,但并未涵盖我的问题。 Also I'd like to avoid using sed or other string replacement methods before I can compare the string -if possible. 另外,如果可以的话,在比较字符串之前,我还要避免使用sed或其他字符串替换方法。 Does anybody know how to compare square brackets in a string in bash? 有人知道如何在bash中比较字符串中的方括号吗?
Also not working: this solution , adapted comparison (maybe I adapted it the wrong way?): 同样不起作用: 此解决方案 ,进行了比较(也许我采用了错误的方式?):
if [[ $hostName != "" ]] && [ "$hostName" != "*[*" ]
This does what you need and is POSIX compatible: 这可以满足您的需求并且与POSIX兼容:
while read hostName
do
if [ "$hostName" ] && [ "$hostName" = "${hostName#[}" ] ; then
echo $hostName
#ssh-keyscan $hostName
fi
done < hosts
Alternative #1: 备选方案1:
while read hostName
do
if [[ $hostName != "" ]] && [[ $hostName != *"["* ]] ; then
echo "$hostName"
#ssh-keyscan $hostName
fi
done < hosts
Alternative #2: 备选方案2:
grep -v '^\[.*\]$' hosts | while read hostName
do
if [[ $hostName != "" ]] ; then
echo "$hostName"
#ssh-keyscan $hostName
fi
done
Alternative #3: 备选方案3:
grep -v '^\[.*\]$' hosts | grep -v '^[ \t]*$' | while read hostName
do
echo "$hostName"
#ssh-keyscan $hostName
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.