extract multiple lines of a file unix

2019-09-03 02:54发布

问题:

I have a file A with 400,000 lines. I have another file B that has a bunch of line numbers.

File B:  
-------
98  
101
25012
10098
23489

I have to extract those line numbers specified in file B from file A. That is I want to extract lines 98,101,25012,10098,23489 from file A. How to extract these lines in the following cases.

  1. File B is a explicit file.
  2. File B is arriving out of a pipe. For eg., grep -n pattern somefile.txt is giving me the file B.

I wanted to use see -n 'x'p fileA. However, I don't know how to give the 'x' from a file. Also, I don't to how to pipe the value of 'x' from a command.

回答1:

sed can print the line numbers you want:

$ printf $'foo\nbar\nbaz\n' | sed -ne '2p'
bar

If you want multiple lines:

$ printf $'foo\nbar\nbaz\n' | sed -ne '2p;3p'
bar
baz

To transform a set of lines to a sed command like this, use sed for beautiful sedception:

$ printf $'98\n101' | sed -e 's/$/;/'
98;
101;

Putting it all together:

sed -ne "$(sed -e 's/$/p;/' B)" A

Testing:

$ cat A
1
22
333
4444
$ cat B
1
3
$ sed -ne "$(sed -e 's/$/p;/' B)" A
1
333

QED.



回答2:

awk fits this task better:

fileA in file case:

awk 'NR==FNR{a[$0]=1;next}a[FNR]' fileB fileA

fileA content from pipe:

cat fileA|awk 'NR==FNR{a[$0]=1;next}a[FNR]' fileB -

oh, you want FileB in file or from pipe, then same awk cmd:

awk '...' fileB fileA

and

cat fileB|awk '...' - fileA