在 bash 中组合表达式和参数扩展



是否可以在 bash 中将参数扩展与算术表达式相结合?例如,我可以在这里做一行来评估lineNumnumChar吗?

echo "Some lines here
Here is another
Oh look! Yet another" > $1
lineNum=$( grep -n -m1 'Oh look!' $1 | cut -d : -f 1 )  #Get line number of "Oh look!"
(( lineNum-- ))                                         # Correct for array indexing
readarray -t lines < $1
substr=${lines[lineNum]%%Y*}                            # Get the substring "Oh look! "
numChar=${#substr}                                      # Get the number of characters in the substring
(( numChar -= 2 ))                                      # Get the position of "!" based on the position of "Y"
echo $lineNum
echo $numChar
> 2
8

换句话说,我是否可以根据单行表达式中另一个字符的位置来获取字符串中一个字符的位置?

至于在与正则表达式匹配的行中获取!的位置Oh look!,只需:

awk -F'!' '/Oh look!/{ print length($1) + 1; quit }' "$file"

您也可以根据自己的喜好进行计算,因此使用原始代码,我认为这将是:

awk -F':' '/^[[:space:]][A-Z]/{ print length($1) - 2; quit }' "$file"

是否可以在 bash 中将参数扩展与算术表达式相结合?

对于计算${#substr},您必须具有子字符串。 因此,您可以:

substr=${lines[lineNum-1]%%.*}; numChar=$((${#substr} - 2))

您还可以编辑grep并由bash完成Y过滤,但awk数量级会更快:

IFS=Y read -r line _ < <(grep -m1 'Oh look!' "$file")
numChar=$((${#line} - 2))

您仍然可以将 3 行合并为:

numChar=$(( $(<<<${lines[lineNum - 1]%%Y*} wc -c) - 1))

最新更新