当构建一个R包时,该命令将进程步骤输出到std。从该输出中,我想获取包的最终名称。
在下面的模拟脚本中,我显示了build命令的输出。需要捕获的部分是从building开始的最后一行。
如何使regex与这些引号匹配,然后将包名捕获到变量中?
#!/usr/bin/env bash
var=$(cat <<"EOF"
Warning message:
* checking for file ‘./DESCRIPTION’ ... OK
* preparing ‘analysis’:
* checking DESCRIPTION meta-information ... OK
* cleaning src
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
Removed empty directory ‘analysis/.idea/inspectionProfiles’
Removed empty directory ‘analysis/.idea/snapshots’
* creating default NAMESPACE file
* building ‘analysis_0.1.tar.gz’
EOF
)
regex="building [\u2018](.*?)?[\u2019]"
if [[ "${var}" =~ $regex ]]; then
pkgname="${BASH_REMATCH[1]}"
echo "${pkgname}"
else
echo "sad face"
fi这应该适用于macOS和CentOS。
发布于 2019-03-15 19:03:44
在Bash4.2中引入了对\u和\U unicode转义的支持。CentOS 7有Bash4.2,因此应该可以在该平台上工作:
regex=$'.*building[[:space:]]+\u2018(.*)\u2019'不幸的是,早期版本的CentOS有旧版本的Bash,我相信MacOS上的Bash的默认版本仍然是3.2。对于这些人,假设引号被编码为UTF-8,这应该是可行的:
regex=$'.*building[[:space:]]+\xe2\x80\x98(.*)\xe2\x80\x99'如果引号是在不同平台上以不同的方式编码的,那么您可以使用替换(例如(\xe2\x80\x98|...)而不是xe2\x80\x98)来匹配所有的可能性(并调整用于BASH_REMATCH的索引)。
有关Bash中Unicode的更多信息,请参见How do you echo a 4-digit Unicode character in Bash?。
我使用$'...'设置正则表达式,因为它支持\x和(来自Bash4.2的)字符转义,而Bash正则表达式不支持字符转义。
关于正则表达式:
.*是为了确保匹配发生在文本的末尾。?,因为它们与Bash的内置正则表达式不兼容。有关Bash正则表达式的信息,请参见mkelement0's excellent answer to How do I use a regex in a shell script?。发布于 2019-03-15 12:33:20
做这件事有很多方法,这是一种:
file=`echo "$var" | grep '^\* building' | grep -o '‘.*’' | head -c -4 | tail -c +4`
echo $file* building开头的行(第一个grep)‘’之间的文本(第二个grep)https://stackoverflow.com/questions/55182568
复制相似问题