Bash

如何匹配單詞並忽略多個空格?

  • February 17, 2021

以下語法應該匹配“Ambari Server running”,但是如果單詞之間有多個空格,如何匹配?如何忽略單詞之間的空格?

echo "Ambari Server      running"  | grep -i "Ambari Server running"
echo "Ambari     Server running"   | grep -i "Ambari Server running"
echo "     Ambari Server running"  | grep -i "Ambari Server running"

預期的結果應該是:

Ambari Server running
Ambari Server running
Ambari Server running

使用tr它的-s選項將連續的空格壓縮成單個空格,然後grep是結果:

$ echo 'Some   spacious  string' | tr -s ' ' | grep 'Some spacious string'
Some spacious string

然而,這不會完全刪除側翼空間,只會將它們壓縮到兩端的單個空間中。

sed用於移除側翼空白以及將內部空白壓縮到單個空間:

echo ' Some   spacious  string' |
sed 's/^[[:blank:]]*//; s/[[:blank:]]*$//; s/[[:blank:]]\{1,\}/ /g'

然後可以將其傳遞給grep.

引用自:https://unix.stackexchange.com/questions/388748