Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the correct onliner for a column filter expression using Perl?

I try to filter expression from a configuration file under Linux mixing bash command line tools and Perl commands in a pipe.

I have a configuration file (see section configuration) and can filter the relevant lines by using `

grep PG.DATABASE database.conf | \
sed -r -e 's/^\s*//;s/\s+/ /'  | \
cut -d ' ' -f2 | \
sort

And get the result as expected:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DB.GRM.CON.LOCAL.V01
DB.GRM.CON.LOCAL.V02
DB.GRM.CON.LOCAL.V03

Now I want to switch to Perl

grep PG.DATABASE database.conf | \
perl -lpe 's/^\s*//; @m = split /\s+/; print $m[1]'  

but I get strange results with a duplication of the input line.

DB.GRM.CON.LOCAL.V01
PG.DATABASE: DB.GRM.CON.LOCAL.V01 BEGIN
DB.GRM.CON.LOCAL.V02
PG.DATABASE: DB.GRM.CON.LOCAL.V02 BEGIN
DB.GRM.CON.LOCAL.V03
PG.DATABASE: DB.GRM.CON.LOCAL.V03 BEGIN

Question

Why is the duplication there and is the correct Perl oneliner for result achieved with the command line tools?

Configuration File

PG.CONFIG: DEFAULT BEGIN

   # Green Rebel Database via PG.SERVICE ------------------------
   PG.DATABASE: DB.GRM.CON.LOCAL.V01 BEGIN
     SERVICE:     'LOC-GRM-V0'
   END.DB.GRM.CON.LOCAL.V01

   # Green Rebel Database via DBI Driver ------------------------
   PG.DATABASE: DB.GRM.CON.LOCAL.V02 BEGIN
     DBI.PG: "dbi:Pg:dbname=grm;host=localhost;port=5432"
     AUTO.COMMIT: FALSE
     RAISE.ERROR: TRUE
     PRINT.ERROR: FALSE
   END.DB.GRM.CON.LOCAL.V02

   # Green Rebel Database via Host, Db, User, Pass --------------
   PG.DATABASE: DB.GRM.CON.LOCAL.V03 BEGIN
     SERVER:     'localhost'
     PORT:        5432
     DATABASE:    'grm'
     USER:        ${/SYSTEM/USER}
     SSL.MODE:    allow
     AUTO.COMMIT: FALSE
     RAISE.ERROR: TRUE
     PRINT.ERROR: FALSE
   END.DB.GRM.CON.LOCAL.V03
END.DEFAULT

>Solution :

I suggest changing the -p option (which makes it automatically print every line) to -n. You can also skip the grep and let perl do it:

perl -lne 'if(/PG\.DATABASE/) {chomp; s/^\s*//; @m = split /\s+/; print $m[1]}' database.conf

A simplification could be:

perl -lne 'print $1 if(/PG\.DATABASE:\s(\S+)/)'  database.conf
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading