Last match

C

Caj Zell

Quite often a colleague asks me if I can help him traverse a file
resulting from debug output and pick out numeric values from some
pattern, comma-separated. For example, he may be interested in the
variable var1 and I tell him to do a little something like this:

perl -n -e 'if(/var1 = (\d+)/){print $1.",\n"};' debug.txt > out.txt

and pick out the last comma.

He's quite allright by this, but I wondered if there is any easy way to
avoid that last comma?
 
D

Dr.Ruud

Caj Zell schreef:

perl -n -e 'if(/var1 = (\d+)/){print $1.",\n"};' debug.txt > out.txt
there is any easy way to avoid that last comma?

1. Push the matches in an array, and print the stringized array with
",\n" as separator.

perl -nle '/var1 = (\d+)/ and push @_, $1 }{ $"=",\n"; print "@_"'

2. Concatenate the matches as ",$1\n", and use substr($s,1).

perl -ne '/var1 = (\d+)/ and $s. = ",$1\n" }{ print substr $s, 1'
 
D

Dr.Ruud

Dr.Ruud schreef:
perl -ne '/var1 = (\d+)/ and $s. = ",$1\n" }{ print substr $s, 1'

The ". =" was meant as " .=".

Variant:

perl -ne '$s .= ",$1\n" if /var1 = (\d+)/ }{ print substr $s, 1'
 
A

attn.steven.kuo

Caj said:
Quite often a colleague asks me if I can help him traverse a file
resulting from debug output and pick out numeric values from some
pattern, comma-separated. For example, he may be interested in the
variable var1 and I tell him to do a little something like this:

perl -n -e 'if(/var1 = (\d+)/){print $1.",\n"};' debug.txt > out.txt

and pick out the last comma.

He's quite allright by this, but I wondered if there is any easy way to
avoid that last comma?


If you have enough memory to slurp the file, then consider:

$ perl -l012 -0777 -ne 'print join ",\n" => /var1 = (\d+)/g;' filename

See 'perldoc perlrun' for details.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top