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

Combine expressions and parameter expansion in bash

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

echo "Some lines here
Here is another
Oh look! Yet another" > 

lineNum=$( grep -n -m1 'Oh look!'  | cut -d : -f 1 )  #Get line number of "Oh look!"
(( lineNum-- ))                                         # Correct for array indexing

readarray -t lines < 

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; quit }' "$file"

您也可以根据自己的喜好进行计算,因此对于您的原始代码,我认为应该是:

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

Is it possible to combine parameter expansion with arithmetic expressions in 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))