【问题标题】:While command in bash "if there's a $string in file.txt... do..."虽然 bash 中的命令“如果 file.txt 中有 $string... 则...”
【发布时间】:2011-12-18 11:24:55
【问题描述】:

需要有关 while 命令的帮助。如果 playlist.txt 中有 $sitename,我想运行命令

这是我的狂欢:

   cat playlist.txt | grep -e "$sitename" |  sed -e "s/^.*\(http:.*"$sitename".*flv\).*$/\1/g" | sort | uniq > checklist.txt
cat checklist.txt

while [ " While can find $sitename in checklist.txt" ]; do
                qa
         done

这就是我已经尝试过的

while [ -n "$echopl" ]; do
                    qa
             done

while [ 'grep -q $string checklist.txt >/dev/null' ]; do
                qa
         done

while [  "grep -q "$string" checklist.txt" ]; do
                qa2
         done
while grep -q "$string" checklist.txt; do
    qa
done

while grep -q '$string' checklist.txt; do
    qa
done


if grep -q "$string" checklist.txt ; then
  qa
fi

我暂时放了很多 if 命令 :(

ifmorelinks ifmorelinks ifmorelinks ifmorelinks ifmorelinks

【问题讨论】:

    标签: linux bash while-loop debian


    【解决方案1】:
    while grep -q "$string" checklist.txt; do
        qa
    done
    

    如果$string 的字面意思是$string 而不是string 变量的值,请使用:

    while grep -q '$string' checklist.txt; do
        qa
    done
    

    【讨论】:

    • 不起作用。已经试过了。即使 checklist.txt 中没有“$string”,qa 也会运行
    • 好吧,那么您的文件仍然包含该字符串。你究竟是如何修改文件的?
    【解决方案2】:
    if grep "$string" checklist.txt >/dev/null 2>&1 ; then
      qa
    fi
    

    【讨论】:

    • 来自 man grep(1):可移植性说明:与 GNU grep 不同,第 7 版 Unix grep 不符合 POSIX,因为它缺少 -q 并且其 -s 选项的行为类似于 GNU grep 的 - q 选项。 USG 风格的 grep 也缺少 -q,但其 -s 选项的行为类似于 GNU grep。可移植的 shell 脚本应该避免使用 -q 和 -s 并且应该将标准和错误输出重定向到 /dev/null。
    • 这个解决方案有一个问题:如果$string包含一个正则表达式元字符,它将被解释!因此,如果您的字符串中有“a.com”,它将与您的清单中的“fatcomparse.org”匹配。你最好改用fgrep,或者grep -F。另外,请考虑-w 选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2022-08-15
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    相关资源
    最近更新 更多