if子句中的Regex多行输出变量



在基于debian的系统上考虑以下内容:

VAR=$(dpkg --get-selections | awk '{print $1}' | grep linux-image)

这将在我的系统上打印一个已安装的包列表,其中包含字符串"linux image",输出如下:

linux-image-3.11.0-17-generic
linux-image-extra-3.11.0-17-generic
linux-image-generic

现在我们都知道

echo $VAR

中的结果

linux-image-3.11.0-17-generic linux-image-extra-3.11.0-17-generic linux-image-generic

echo "$VAR"

中的结果

linux-image-3.11.0-17-generic
linux-image-extra-3.11.0-17-generic
linux-image-generic

我不想在if子句中使用外部命令,它看起来很脏,也不太优雅,所以我想使用正则表达式匹配中内置的bash:

if [[ "$VAR" =~ ^linux-image-g ]]; then
   echo "yes"
fi

然而,这并不起作用,因为这里似乎没有考虑多行。如何匹配变量中行的开头?

if语句中使用外部命令没有错;我会完全跳过VAR变量并使用

if dpkg --get-selections | awk '{print $1}' | grep -q linux-image;

grep-q选项抑制其输出,而if语句直接使用grep的退出状态。您也可以直接在awk脚本中删除grep并测试$1

if dpkg --get-selections | awk '$1 =~ "^linux-image" { exit 0; } END {exit 1}'; then

或者您可以跳过awk,因为在调用grep:之前似乎不需要删除其他字段

if dpkg --get-selections | grep -q '^linux-image'; then

最新更新