Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash shell脚本Grep-f in for循环_Bash_For Loop_Grep - Fatal编程技术网

Bash shell脚本Grep-f in for循环

Bash shell脚本Grep-f in for循环,bash,for-loop,grep,Bash,For Loop,Grep,需要grep-f在for循环中运行的帮助吗 基本上,对于name.txt中的每个条目,我希望grep.txt中的所有行,并在单独的文件中写出 比如说 1) name.txt是以下三个名称的列表 America Europe Asia 2) A.txt为(制表符分隔) 现在从name.txt文件中提取每个条目,在A.txt中搜索相应的行,并在三个单独的输出文件中返回: file1: X y Z America y b c America a b c Americ

需要grep-f在for循环中运行的帮助吗

基本上,对于name.txt中的每个条目,我希望grep.txt中的所有行,并在单独的文件中写出

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

America
Europe   
Asia
2) A.txt为(制表符分隔)

现在从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
head file[123]
可能是用脚本编写并用bash执行

提前感谢

运行以下脚本(如./script.sh name.txt input.txt),其中name.txt具有名称,input.txt是您的输入文件。输出文件保存为文件_America.txt、文件_Asia.txt和文件_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"
#/bin/bash-x
读行时;做
#跳过空行
[-z“$line”]&继续;
#运行grep并保存输出
grep“$line”“$2”>文件_$line.txt;
完成<“$1”

单向使用
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
结果如下:

==> 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

==>file1 file2 file3无用地使用了
cat
。在读取行时使用输入重定向:
;做读行时完成<“$1”
@chepner:或
<$1;做完成
。是的,重定向可以在命令之前进行,在这种情况下,它使命令更清晰。
==> 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