bash中的表达式和参数扩展

问题描述 投票:2回答:1

是否有可能在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

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

bash arithmetic-expressions parameter-expansion
1个回答
1
投票

关于在与!正则表达式匹配的行中获取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,并由Ybash进行过滤,但是awk的幅度会更快:

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

仍然可以将三行合并为:

numChar=$(( $(<<<${lines[lineNum - 1]%%Y*} wc -c) - 1))
© www.soinside.com 2019 - 2024. All rights reserved.