【问题标题】:Grep for a dollar sign within backticks反引号内的美元符号的 Grep
【发布时间】:2014-06-20 14:00:01
【问题描述】:

我有一个这样的文件

文件名:hello.txt

{1:ABC}{2:BCD}{3:{108:20140619-2}}{4:
:97A::Hi//12345
:97A::Hi//12345
:93B::Hello//FAMT/00000,
:16S:FIN
-}{5:{CHK:BDG6789}}{S:{ABC:}{DEF:S}{WOM:ONHGRT}}

现在基本上我正在使用下面的 if 语句检查 $ 符号以及 :97A: AND im 的存在。

if [ `grep -c '\$' hello.txt` -gt 0 ] && [ `grep -c ":97A:" hello.txt` -gt 1 ]
then
echo "condition satisfied"
else
echo "condition not satisfied"
fi

如果我执行这个我得到满足条件的回显语句。但是 id 应该是相反的 :( 因为我把 AND 条件。请帮忙。

【问题讨论】:

  • 这应该做什么(英文,不是代码)?
  • 基本上我会收到带有 $ 符号的消息,所以我正在检查它的存在,因为它在这里不存在,它应该给出不满足的回显条件。?
  • grep -c '\$' hello.txtgrep -c ":97A:" hello.txt的输出是什么?这是你所期望的吗?

标签: linux shell unix grep


【解决方案1】:

我也不明白你在问什么,但从你的代码中我得出结论,你在寻找美元符号时遇到了麻烦。如果您使用反引号,我想您也需要转义反斜杠:

$ echo 'foo$bar' > dollar.txt
$ echo 'foo_bar' > no_dollar.txt

$ [ `grep -c '\$' dollar.txt` -gt 0 ] && echo 1
1

$ [ `grep -c '\$' no_dollar.txt` -gt 0 ] && echo 1
1

$ [ `grep -c '\\$' dollar.txt` -gt 0 ] && echo 1
1

$ [ `grep -c '\\$' no_dollar.txt` -gt 0 ] && echo 1

$ [ `grep -c '\\$' no_dollar.txt` -gt 0 ] || echo 0
0

或者,使用$() 代替反引号

【讨论】:

  • 您必须在反引号命令替换中使用双反斜杠,因为那里有一个额外的反斜杠删除级别,以允许反斜杠反引号充当嵌套的反引号对。 $() 不需要这个,因为它是自然可嵌套的。
【解决方案2】:

grep -c '\$' hello.txt 替换为grep -c '\\$' hello.txt 然后它将按需要工作。

例如:

bash -x test.sh 
++ grep -c '\$' hello.txt
+ '[' 0 -gt 0 ']'
+ echo 'condition not satisfied'
condition not satisfied

PS:bash -x 是你的朋友 :)

【讨论】:

  • 嗨蒂亚戈请检查我的评论
【解决方案3】:

我建议使用$ 语法在子shell 中执行grep 命令,然后进行比较。在我看来,这是一种更简洁的方式,并且要求你不再是逃避艺术家。

if [ $(grep -c '\$' hello.txt) -gt 0 ] && [ $(grep -c ":97A:" hello.txt) -gt 1 ]
then
echo "condition satisfied"
else
echo "condition not satisfied"
fi

对于您的hello.txt,输出将是:

>> bash test.bash 
condition not satisfied

因为您的文件中没有美元符号

[ $(grep -c '\$' hello.txt) -gt 0 ]

会测试

[ 0 -gt 0 ]

并产生假,而

[ $(grep -c ':97A' hello.txt) -gt 1 ]

会测试

[ 2 -gt 1 ]

并返回 true。最后, false && true 将产生 false 并执行第二个 echo 语句。

【讨论】:

    【解决方案4】:

    "我正在检查 $ 符号是否存在"

    第一个条件不匹配,因为您的输入中没有“$”符号,因此第一个 grep 的输出为 0。由于 0 不大于 0,因此结果为“false”。因此,第二个子句根本不会被执行。 “条件不满足”,因为您对“满足”的要求是:输入同时包含“$”和“:97A:”。

    对于grep是否匹配任何行的结果,您不需要计算匹配数。

    if grep -q '\$' file; then ...
    

    是一种在没有 rube-goldbergismns 的条件语句中使用 grep 结果的方法

    【讨论】:

      【解决方案5】:

      使用awk 并且只读取一次文件:

      if awk '/[$]/{d++} /:97A:/{o++} END{exit !(d && o>1)}' hello.txt; then
          echo "condition satisfied"
      else
          echo "condition not satisfied"
      fi
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-15
        • 1970-01-01
        • 2018-06-19
        • 2021-08-07
        • 1970-01-01
        • 2015-06-24
        • 2023-04-06
        相关资源
        最近更新 更多