【问题标题】:shell script Grep -f in for loop在 for 循环中的 shell 脚本 Grep -f
【发布时间】:2012-08-08 01:53:42
【问题描述】:

grep -f 需要帮助才能在 for 循环中运行

基本上对于 name.txt 中的每个条目,我想从 A.txt 中提取所有行并在单独的文件中写出

例如 1) name.txt 是以下三个名称的列表

America
Europe   
Asia

2) A.txt 是(制表符分隔)

X y Z America
x a b Asia
y b c America
a b c Europe
x y z Europe
a b c America

现在从 name.txt 文件中获取每个条目,在 A.txt 中搜索相应的行并返回三个单独的输出文件:

file1: X y Z America
       y b c America
       a b c America

file2: a b c Europe
       x y z Europe
file3: x a b Asia

可能是用脚本编写并用 bash 执行?

提前致谢!!!

【问题讨论】:

    标签: bash for-loop grep


    【解决方案1】:

    运行以下脚本(如 ./script.sh name.txt input.txt),其中 name.txt 包含名称,而 input.txt 是您的输入文件。输出文件保存为 file_America.txt、file_Asia.txt 和 file_Europe.txt

    #!/bin/bash -x
    
    while read line; do
    #skip empty line
    [ -z "$line" ] && continue;
    #run grep and save the output
    grep "$line" "$2" > file_$line.txt;
    done < "$1"
    

    【讨论】:

    • cat 的无用使用。使用输入重定向:while read line; do ...; done &lt; "$1"
    • @chepner:或&lt; $1 while read line; do ...; done。是的,重定向可以在命令之前进行,在这种情况下它会更清晰。
    【解决方案2】:

    一种使用awk的方式:

    awk '
        ## Process first file of arguments. Save data in an array, the name as
        ## key, and the number of the output file to write as value.
        FNR == NR {
            name[ $1 ] = FNR;
            next;
        }
    
        ## Process second file of arguments. Check last field of the line in the 
        ## array and print to file matched by the value.
        FNR < NR {
            print $0 > sprintf( "%s%d", "file", name[ $NF ] );
        }
    ' name.txt A.txt
    

    检查输出文件:

    head file[123]
    

    结果如下:

    ==> file1 <==
    X y Z America
    y b c America
    a b c America
    
    ==> file2 <==
    a b c Europe
    x y z Europe
    
    ==> file3 <==
    x a b Asia
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2022-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 2011-08-03
      • 1970-01-01
      相关资源
      最近更新 更多