Text Processing – How to Remove Lines with Specific Line Numbers

awksedtext processing

I have a text file A which contains line numbers which I want to remove from text file B. For example, file A.txt contains lines

1
4
5

and file B.txt contains lines

A
B
C
D
E

The resulting file should be:

B
C

Of course, this can be done manually with

sed '1d;4d;5d' B.txt

but I wonder how to do it without specifying line numbers manually.

Best Answer

You can use awk as well:

awk 'NR==FNR { nums[$0]; next } !(FNR in nums)' linenum infile

in specific case when 'linenum' file might empty, awk will skip it, so it won't print whole 'infile' lines then, to fix that, use below command:

awk 'NR==FNR && FILENAME==ARGV[1]{ nums[$0]; next } !(FNR in nums)' linenum infile

or even better (thanks to Stéphane Chazelas):

awk '!firstfile_proceed { nums[$0]; next } 
     !(FNR in nums)' linenum firstfile_proceed=1 infile
Related Question