如何编写for循环以将数据提取到新创建的文件? [英] How to write for loop to fetch data to newly created file?
问题描述
我有一种情况,我想从上面匹配的那一行中获取以上两行
I have scenario where I want to fetch the above 2 lines from where it as matched
我有两个文件:
文件1
Ag
Ab
Ah
Av
Ax
文件2
jb:fun_0
jb:fun_jack_0
jb1:Ag
jb:fun_1
jb:fun_jack_1
jb1:Ab
jb:fun_2
jb:fun_jack_3
jb1:Ai
jb:fun_4
jb:fun_jack_4
jb1:Ah
jb:fun_5
jb:fun_jack_5
jb1:Av
jb:fun_5
jb:fun_jack_5
jb1:Al
jb:fun_5
jb:fun_jack_5
jb1:Aj
jb:fun_5
jb:fun_jack_5
jb1:Ax
我想添加for循环=>喜欢
I want to add for loop => like
首先它将使用file1 =>中的单词,就像Ag =>尝试在文件2 =>如果找到匹配项,则应将匹配的那两行以上写入新的文本文件=> demo.txt
first it will take the word from file1 => like Ag => try to find Ag in the file 2 => if match found then above 2 lines from where it as match should be written to a new text file => demo.txt
我的代码
for j in file1
do
sr=`grep -i -B2 '$j' file2`
echo $sr>>demo.txt
done
但是上面的代码不起作用=>建议我
But the above code is not working => suggest me
预期输出:在文件2 =>上面两行匹配中发现的Ag匹配应该被打印
expected output: Ag match found in file2 => above 2 lines of match should be printed
类似输出:
=======================
jb:fun_0 # 1st line
jb:fun_jack_0 # 2nd line
jb1:Ag # => match found
=======================
jb:fun_1 # 1st line
jb:fun_jack_1 # 2nd line
jb1:Ab # => match found
=======================
应该打印出如何匹配两行以上的输出
that how the output will on match above 2 lines should be printed
推荐答案
您可以使用以下内容:
grep -wFB2 -f file2 file1 > demo.txt
grep 选项的详细信息:
Detail of the grep
options :
-
-w
仅匹配完整单词:寻找Av
时,请避免匹配 -
-B2
输出除匹配行之外的前两行 -
-f file2
从file2读取模式 -
-F
模式是换行分隔的纯文本,而不是正则表达式
Avoid
-w
match only full words : avoid matchingAvoid
when looking forAv
-B2
output the two previous lines in addition to matching lines-f file2
read patterns from file2-F
the patterns are linefeed-separated plain text, not regexs
您可以在此处尝试!
这篇关于如何编写for循环以将数据提取到新创建的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!