目前正在寻找更好的方法…
例如,我有一个文件,其中包含一个分支名称或版本号的字符串。我想知道文件是否在ref
模式之后没有使用版本号。
示例文件:
source = "git::https://URL?ref=main"
source = "git::https://URL?ref=0.1.0"
目前我是这样做的:
# Search for string after pattern and turn it into an array.
version=($(grep -oP '(?<=ref=).*' file.txt | tr -d '".'))
# If array does not contain number pattern, catch it.
if [[ $version =~ ^[0-9]+(.[0-9]+){2,3}$ ]]
then
echo "All module sources contain versions, will continue"
else
echo "Some module sources DO NOT contain versions, you must use a version number in your module source"
fi
我怎么能做到这一点与grep单独,甚至不得不导出字符串到数组?
最后是
if [[ $(grep -oPr '(?<=ref=).*' | tr -d '"') =~ ^[0-9]+(.[0-9]+){2,3}$ ]]
then
echo "All module sources contain versions, will continue"
else
echo "Some module sources DO NOT contain versions, you must use a version number in your module source"
fi
对于GNUgrep
和PCRE正则表达式,您可以使用
#!/bin/bash
rx='ref=(?![0-9]+(.[0-9]+){2,3}")[^"]*"'
if grep -Pq "$rx" file.txt; then
echo "Some module sources DO NOT contain versions, you must use a version number in your module source"
else
echo "All module sources contain versions, will continue"
fi
参见在线演示。正则表达式的意思是
ref=
- aref=
text(?![0-9]+(.[0-9]+){2,3}")
-如果有一个或多个数字后面出现两次或三次点和一个或多个数字,则会导致匹配失败[^"]*"
- 0个或多个"
以外的字符,然后是"
字符。
if grep -E 'ref=[0-9].[0-9]{2,3}$' file.txt; then
echo has version
else
echo has no version
Grep有一个--invert-match
选项(又名-v
),所以您可以查找不匹配您的模式的行,如果搜索成功,您将知道您有不兼容的行:
if grep -vqE 'ref=d+(.d+)*"' file.txt; then
echo "Some module sources DO NOT contain versions, you must use a version number in your module source"
else
echo "All module sources contain versions, will continue"
fi