【发布时间】:2020-09-16 17:37:35
【问题描述】:
是否可以在bash中将参数扩展与算术表达式结合起来?例如,我可以在这里单线评估lineNum 或numChar 吗?
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
换句话说,我可以根据单行表达式中另一个字符的位置来获取一个字符在字符串中的位置吗?
【问题讨论】:
-
substr=${lines[lineNum--]%%.*}; numChar=$(( ${#substr} - 2))?请创建一个minimal reproducible example。For context将上下文作为代码提供会更容易:echo 'some lines' > "$1"; lines=( bla ble bly )然后从您的代码中提供预期的输出,因此它将创建一个 minimal reproducible example。 -
@KamilCuk 谢谢你的评论。我相应地编辑了我的帖子。请让我知道这是否足够好。另外,谢谢您的回答:我不知道
numChar=$(( ${#substr} - 2)是允许的。 -
如果
lines包含文件的内容,你不能只测量已经在替换中的子字符串吗?Get the position of "!" based on the position of "Y"- 只是得到!的位置,所以所有这些计算只是为了得到!在包含Oh look!的行中的位置?为什么Y会被过滤?10正确吗?我在Oh look!的第7 个字符处看到!? -
@KamilCuk 你的意思是像:
substr=${#lines[lineNum]%%Y*}? -
@KamilCuk 我尝试的最小可重现示例只是对问题有任意情况。我无法在完整脚本中使用这些快捷方式。此外,测试
${#lines[lineNum]%%!*}给了我整行的长度而不是子字符串的长度。
标签: bash arithmetic-expressions parameter-expansion