justaguy
justaguy

Reputation: 3022

print specific lines from text file using perl

I am trying to print a few lines from a file in which the lines are in separate rows. I don't think the below perl is the best way but hopefully it is a start

perl -ne 'if ($. == 5) ($. == 6) ($. == 7) ($. == 10) {print;exit}' file.txt

file

#Sample = xxxxx
#Sample Type = xxxxxx
#Build = xxxxxxx
#Platform = xxxxxxx
#Display Name= XXXXX  (keep this field without the #)
#identifier = xxxxxx  (keep this field without the #)
#Gender = xxxxx       (keep this field without the #)
#Control Gender = xxxxx
#Control Sample = xxxxx
#Quality = X.XXXXXX   (keep this field without the # and X.XXX)

desired output

Display Name= XXXXX  (keep this field without the #)
identifier = xxxxxx  (keep this field without the #)
Gender = xxxxx       (keep this field without the #)
Quality = X.XXXXXX   (keep this field without the # and X.XXX)

Upvotes: 1

Views: 2042

Answers (3)

Borodin
Borodin

Reputation: 126722

Rather than specifying the numbers of the lines you want to retain, it's much clearer to identify them by the text they contain

Like this

perl -ne 'print $1 if /^#((Display Name|identifier|Gender|Quality).*)/is' myfile

output

Display Name= XXXXX
identifier = xxxxxx
Gender = xxxxx
Quality = X.XXXXXX

I don't understand what you mean by the comment on the last line of data "keep this field without the # and X.XXX". Do you mean "without the # or the X.XXX"? It's strange if you just want Quality = here

Upvotes: 1

bart
bart

Reputation: 898

You can use 'smartmatch' operator for this task:

perl -ne 's/^#//; @n = (5, 6, 7, 10); print if $. ~~ @n'  file.txt

Upvotes: 1

Miguel Prz
Miguel Prz

Reputation: 13792

perl -ne 'print if $.==5 || $.==6 || $.==7 || $.==10' file.txt

Upvotes: 0

Related Questions