string bash 在文件的每一行中搜索字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5695916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:04:10  来源:igfitidea点击:

bash search for string in each line of file

bashstringfile-io

提问by Joshua Noble

I'm trying what seems like a very simple task: use bash to search a file for strings, and if they exist, output those to another file. It could be jetlag, but this should work:

我正在尝试一个看起来很简单的任务:使用 bash 搜索文件中的字符串,如果存在,将它们输出到另一个文件。这可能是时差,但这应该有效:

#!/bin/bash

cnty=CNTRY

for line in $(cat wheatvrice.csv); do
    if [[ $line = *$cnty* ]]
    then
        echo $line >> wr_imp.csv
    fi
done

I also tried this for completeness:

为了完整性,我也试过这个:

#!/bin/bash

cnty=CNTRY

for line in $(cat wheatvrice.csv); do
    case $line in 
    *"$cnty"*) echo $line >> wr_imp.csv;;
    *) echo "no";;
    esac
done

both output everything, regardless of whether the line contains CNTRY or not, and I'm copy/pasting from seemingly reliable sources, so apparently there's something simple about bash-ness that I'm missing?

两者都输出所有内容,无论该行是否包含 CNTRY,而且我是从看似可靠的来源复制/粘贴的,所以显然我缺少一些关于 bash-ness 的简单内容?

回答by Ignacio Vazquez-Abrams

Don't use bash, use grep.

不要使用 bash,使用 grep。

grep -F "$cnty" wheatvrice.csv >> wr_imp.csv

回答by user unknown

While I would suggest to simply use grep too, the question is open, why you approach didn't work. Here a self referential modification of your second approach - with keyword 'bash' to match itself:

虽然我也建议简单地使用 grep,但问题是开放的,为什么你的方法不起作用。这是第二种方法的自引用修改 - 使用关键字“bash”来匹配自身:

#!/bin/bash

cnty=bash    
while read -r line
do
    case $line in 
        *${cnty}*) 
            echo $line " yes" >> bashgrep.log
            ;;
        *)
                echo "no"
                ;;
    esac
done < bashgrep.sh

The keypoint is while read -r line ... < FILE. Your command with cat involves String splitting, so every single word is processed in the loop, not every line.

关键是while read -r line ... < FILE。您的 cat 命令涉及字符串拆分,因此循环中处理每个单词,而不是每一行。

The same problem in example 1.

示例 1 中的相同问题。