【问题标题】:Combine expressions and parameter expansion in bash在bash中组合表达式和参数扩展
【发布时间】:2020-09-16 17:37:35
【问题描述】:

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

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

【问题讨论】:

  • substr=${lines[lineNum--]%%.*}; numChar=$(( ${#substr} - 2))?请创建一个minimal reproducible exampleFor context 将上下文作为代码提供会更容易:echo 'some lines' &gt; "$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


【解决方案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 并让 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))

【讨论】:

  • 非常感谢。 &lt;&lt;&lt; 这里的目的是什么?也感谢您提供更简单的 awk 解决方案。
  • 称为“这里字符串”,目的是将${lines[...]}扩展的结果重定向到wc -c命令的标准输入。
猜你喜欢
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多