【问题标题】:Concatenating xargs with the use of if-else in bash在 bash 中使用 if-else 连接 xargs
【发布时间】:2015-10-26 04:18:51
【问题描述】:

我有两个测试文件,ttt.txt和ttt2.txt,内容如下:

 #ttt.txt
 (132) 123-2131
 543-732-3123
 238-3102-312


 #ttt2.txt
 1
 2
 3

我已经在 bash 中尝试过以下命令,效果很好:

if grep -oE "(\(\d{3}\)[ ]?\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})" ttt1.txt ; then echo "found"; fi
# with output 'found'

if grep -oE "(\(\d{3}\)[ ]?\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})" ttt2.txt ; then echo "found"; fi

但是当我将上述命令与 xargs 结合使用时,它会报错“-bash: syntax error near unexpected token `then'”。谁能给我一些解释?提前致谢!

ll | awk '{print $9}' | grep ttt | xargs -I $  if grep --quiet -oE "(\(\d{3}\)[ ]?\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})" $; then echo "found"; fi

【问题讨论】:

    标签: linux bash


    【解决方案1】:

    $ 是 bash 中的一个特殊字符(它标记变量)所以不要将它用作你的 xargs 标记,你只会感到困惑。

    这里真正的问题是您将if grep --quiet -oE "(\(\d{3}\)[ ]?\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})" $ 作为参数传递给xargs,然后该行的其余部分被视为新命令,因为它在; 处中断。

    您可以将整个内容包装在 bash 的子调用中,以便 xargs 看到整个命令:

    $ ll | awk '{print $9}' | grep ttt | xargs -I xx bash -c 'if grep --quiet -oE "(\(\d{3}\)[ ]?\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})" xx; then echo "found"; fi'
    found
    

    最后,ll | awk '{print $9}' | grep ttt 是列出您要查找的文件的一种不必要的复杂方式。你实际上不需要上面的任何代码,只需这样做:

    $ if grep --quiet -oE "(\(\d{3}\)[ ]?\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})" ttt*; then echo "found"; fi
    found
    

    或者,如果您想依次处理每个文件(此处不需要,但当事情变得更复杂时您可能需要):

    for file in ttt*
    do
        if grep --quiet -oE "(\(\d{3}\)[ ]?\d{3}-\d{4})|(\d{3}-\d{3}-\d{4})" "$file"
        then
            echo "found"
        fi
    done
    

    【讨论】:

    • 谢谢!这是非常详细和有用的:]
    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多