linux - 匹配 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
我在代码中做错了什么?
解决方案
要匹配的模式应该在=~
表达式的右侧:
if [[ "$line" =~ ^APC0001 ]]
then
echo $line
exit 1
fi
查看bash 手册/条件结构[[...]]
中的部分。
作为旁注,你不需要cat
那里。做就是了:
while read -r line
do
# ...
done < /home/xxxx/xxxx/some_file.txt
推荐阅读
- spring-boot - 缺少必需的加密配置属性:jasypt.encryptor.password
- javascript - 反向数组不使用反向
- javascript - How to include new google material design icon inside node modules?
- android - Android kotlin将列表行分配给变量错误
- sql-server - SQL Function to Increment 6 character ISO date field with format 'YYYYWW'
- javascript - How to preserve dot using split and negative lookahead
- gatling - Gatling overrides `Cookie` header with the `Set-Cookie` header of previous response
- mysql - Convert a string of comma separated values into values for mysql stored procedure
- javascript - 如何使用按钮显示所选图像
- javascript - 如何在Javascript中获取大浮点数的前两位