[英]Trying to use variable in sed or awk
I have 2 separate text files, each in the same exact format. 我有2个单独的文本文件,每个文件都具有相同的格式。 I can grep
FILE1.txt
for a specific search term and output the line numbers of every match. 我可以grep
FILE1.txt
获取特定的搜索词,并输出每个匹配的行号。 The line numbers are outputted in numeric order to a file or a variable. 行号以数字顺序输出到文件或变量。
I want use each line number and print that line from FILE2.txt
in numeric order to a single OUTPUT.txt
. 我想使用每个行号并将数字顺序从
FILE2.txt
打印到单个OUTPUT.txt
。 Does anyone know a way, using awk
or sed
to do this? 有没有人知道一种方式,使用
awk
或sed
这样做?
I have a string variable $linenumbers with values of 25 26 27 28. 我有一个字符串变量$ linenumbers,值为25 26 27 28。
I use the following command: 我使用以下命令:
for i in $linenumbers;
我在$ linenumbers; do sed -n "/$I/p" $i test_read2.fastq >> test.fastq;
do sed -n“/ $ I / p”$ i test_read2.fastq >> test.fastq; done.
完成。
I get errors of 我得到了错误
sed: can't read 25: No such file or directory sed:无法读取25:没有这样的文件或目录
sed: can't read 26: No such file or directory sed:无法读取26:没有这样的文件或目录
sed: can't read 27: No such file or directory sed:无法读取27:没有这样的文件或目录
sed: can't read 28: No such file or directory sed:无法读取28:没有这样的文件或目录
If I do this sed command one by one, I can pull line number 25, 26, 27 and 28 from the file and print it to file using the following command; 如果我逐个执行此sed命令,我可以从文件中提取行号25,26,27和28,并使用以下命令将其打印到文件中;
sed -n "25p" test_read2.fastq >> test.fastq
sed -n“25p”test_read2.fastq >> test.fastq
I want to replace "25p" with variable so it pulls out multiple lines (25,26,27,28) from the file without doing this one by one... 我想用变量替换“25p”,所以它从文件中拉出多行(25,26,27,28),而不是一个一个地执行此操作...
Try this: 尝试这个:
grep -n interesting FILE1.txt | cut -d: -f1 | while read l
do
sed -n "$l p" FILE2.txt
done
Example: 例:
$ cat FILE1.txt
foo
bar
baz
$ cat FILE2.txt
qux
quux
quuux
$ grep -n bar FILE1.txt | cut -d: -f1 | while read l; do sed -n "$l p" FILE2.txt; done
quux
Not sure what exactly you want to do. 不确定你到底想做什么。 If you want to print the lines of
file
which are defined in lines
you could do awk 'NR==FNR{a[$0];next}FNR in a' lines file
如果你想打印行中定义的
file
lines
你可以awk 'NR==FNR{a[$0];next}FNR in a' lines file
test: 测试:
$ cat lines
1
3
7
$ cat file
a
b
c
d
e
f
g
$ awk 'NR==FNR{a[$0];next}FNR in a' lines file
a
c
g
sed -n "` grep -n 'Yourpattern' File1.txt | sed 's/:.*/p/'`" File2.txt
是carefful在替代和(双)报价YourPattern
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.