【问题标题】:Assign grep count to variable将 grep 计数分配给变量
【发布时间】:2013-04-25 23:51:58
【问题描述】:

如何分配结果

grep -c "some text" /tmp/somePath

放入变量中,以便我可以回显它。

#!/bin/bash
some_var = grep -c "some text" /tmp/somePath
echo "var value is: ${some_var}"

我也试过了:

some_var = 'grep -c \"some text\" /tmp/somePath'

但我不断收到:command not found。

【问题讨论】:

标签: bash shell grep


【解决方案1】:

要分配命令的输出,请使用var=$(cmd)(因为shellcheck 会自动告诉您是否将脚本粘贴到那里)。

#!/bin/bash
some_var=$(grep -c "some text" /tmp/somePath)
echo "var value is: ${some_var}"

【讨论】:

  • 谢谢您的回答。但是如何在代码的可执行部分中使用输入变量呢? my_var=$(grep "word" $1) - 无效
【解决方案2】:


发现问题
它的任务,这将工作:

some_var=$(command)


虽然这行不通:

some_var = $(command)


感谢您的帮助!我会接受第一个有用的答案。

【讨论】:

  • 不能给这个足够的投票......这些是让我感激的答案类型。
  • 非常感谢您的见解。同意查理。对此投票不够。
【解决方案3】:
some_var=$(grep -c "some text" /tmp/somePath)

来自man bash:

   Command substitution allows the output of a command to replace the com‐
   mand name.  There are two forms:

          $(command)
   or
          `command`

   Bash performs the expansion by executing command and replacing the com‐
   mand substitution with the standard output of  the  command,  with  any
   trailing newlines deleted.

【讨论】:

  • 变量赋值不能在=周围有空格。
  • @michaelb958 你是对的。在我发现问题之前,我的帖子已修复。
  • 这是问题所在:)
猜你喜欢
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多