Extract multiple lines of unix file

I have file A with 400,000 lines. I have another B file that has a series of lines in it.

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

I need to extract these line numbers indicated in file B from file A. This I want to extract lines 98,101,25012,10098,23489 from file A. How to extract these lines in the following cases.

  • File B is an explicit file.
  • File B comes from the pipe. For example, grep -n pattern somefile.txt gives me file B.

I wanted to use see -n 'x'p fileA. However, I do not know how to pass the "x" from the file. Also, I cannot pass the value of "x" from the command.

0
source share
2 answers

sed can print the line numbers you want:

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

If you want some lines:

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

To convert a rowset to a sed command like this, use sed for a nice sed ception:

 $ 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

+1
source

awk is better suited for this task:

fileA in file:

 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 a file or from a channel, then awk cmd:

 awk '...' fileB fileA 

and

 cat fileB|awk '...' - fileA 
+1
source

Source: https://habr.com/ru/post/1012316/


All Articles