Awk 不改变顺序的连续行
我期待着grep文件1与相同的顺序和两个以上的连续行。我试过这个:Awk 不改变顺序的连续行,awk,grep,Awk,Grep,我期待着grep文件1与相同的顺序和两个以上的连续行。我试过这个: cat file1 4 8 7 cat file2 4.999286 12.669064 0.000000 5.999343 12.753258 0.000000 6.999401 12.654514 0.000000 7.999458 12.774485 0.000000 8.999515 12.662147 0.000000 9.9
cat file1
4
8
7
cat file2
4.999286 12.669064 0.000000
5.999343 12.753258 0.000000
6.999401 12.654514 0.000000
7.999458 12.774485 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
10.999629 12.717721 0.000000
我希望输出如下:
grep -A 2 -Ff file1 file2
grep
对于很少的文件扫描速度很快
4.999286 12.669064 0.000000
5.999343 12.753258 0.000000
6.999401 12.654514 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
10.999629 12.717721 0.000000
7.999458 12.774485 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
$while IFS=read-r n;dogrep-A2“^$n”文件2;完成<文件1
4.999286 12.669064 0.000000
5.999343 12.753258 0.000000
6.999401 12.654514 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
10.999629 12.717721 0.000000
7.999458 12.774485 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
请您尝试以下操作,这将以输入文件1中出现$1
的相同顺序给出结果
$ while IFS= read -r n; do grep -A2 "^$n." file2; done < file1
4.999286 12.669064 0.000000
5.999343 12.753258 0.000000
6.999401 12.654514 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
10.999629 12.717721 0.000000
7.999458 12.774485 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
解释:为上述代码添加解释
awk '
BEGIN{
s1="\""
}
FNR==NR{
a[$0]
next
}
(int($1) in a){
system("grep -A2 " s1 $0 s1 OFS FILENAME)
}
' Input_file1 Input_file2
输出如下
awk ' ##Starting awk program here.
BEGIN{ ##Starting BEGIN section of code here.
s1="\"" ##Creating a variable named s1 whose value is "
} ##Closing BEGIN section of awk code here.
FNR==NR{ ##Checking condition if FNR==NR, which will be only TRUE when Input_file1 is being read.
a[$0] ##Creating an array named a whose index is $0.
next ##next will skip all further statements from here.
} ##Closing BLOCK for FNR==NR condition here.
(int($1) in a){ ##Checking condition if integer value of $1 is present in array a then do following.
system("grep -A2 " s1 $0 s1 OFS FILENAME) ##Using system command to run grep command which will print 2 lines after match of current line in current Input_file name passed to grep by FILENAME variable of awk.
} ##Closing BLOCK of condition.
' Input_file1 Input_file2 ##Mentioning Input_file names here.
这可能适合您(GNU&):
使用file1作为输入并保持原始顺序,grepfile2并行执行多次
或者,如果您愿意,可以是:
parallel -k grep -A2 '^{}' file2 :::: file1
或:
@莫德,你能告诉我这是否对你有帮助吗?如果这对你有帮助,你能检查一下我的答案吗?
parallel -k grep -A2 '^{}' file2 :::: file1
parallel -a file1 -k grep -A2 '^{}' file2
cat file1 | parallel -k grep -A2 '^{}' file2