首页 > 解决方案 > 匹配 if 条件中的字符串

问题描述

我有一个some_file.txt包含以下内容的文件:

APC000101052019
APC000201052019
APC000301052019
APC000401052019
APC000501052019

现在我正在尝试匹配APC0001以下脚本:

#!/bin/bash

cat /home/xxxx/xxxx/some_file.txt|while read -r line
do
    if [[ "APC0001" =~ "$line" ]]
    then
        echo $line
        exit 1
    fi
done

但我没有得到预期的输出,下面是我得到的输出:

+ cat /home/xxxx/xxxx/some_file.txt
+ read -r line
+ [[ APC0001 =~ APC000101052019]]
+ read -r line
+ [[ APC0001 =~ APC000201052019]]
+ read -r line
+ [[ APC0001 =~ APC000301052019]]
+ read -r line
+ [[ APC0001 =~ APC000401052019]]
+ read -r line
+ [[ APC0001 =~ APC000501052019]]
+ read -r line

我在代码中做错了什么?

标签: linuxbashwhile-loop

解决方案


要匹配的模式应该在=~表达式的右侧:

if [[ "$line" =~ ^APC0001 ]]
    then
        echo $line
        exit 1
    fi

查看bash 手册/条件结构[[...]]中的部分。

作为旁注,你不需要cat那里。做就是了:

while read -r line
do
    # ...
done < /home/xxxx/xxxx/some_file.txt

推荐阅读