Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl one-liner to extract groups of characters

Tags:

perl

I am trying to extract a group of characters with a Perl one-liner, but I have been unsuccessful:

echo "hello_95_.txt" | perl -ne 's/.*([0-9]+).*/\1/'

Returns nothing, while I would like it to return 95. How can I do this with Perl?

Update:

Note that, in contrast to the suggested duplicate, I am interested in how to do this from the command-line. Surely this looks like a subtle difference, but it's not straightforward unless you already know how to effectively use Perl one-liners.

Since people are asking, eventually I want to learn to use Perl to write powerful one-liners, but most immediately I need a one-liner to extract consecutive digits from each line in a large text file.

like image 706
Amelio Vazquez-Reina Avatar asked Jul 15 '13 22:07

Amelio Vazquez-Reina


People also ask

What is * in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.

What is $1 Perl?

$1 equals the text " brown ".

What is G in Perl?

The “g” stands for “global”, which tells Perl to replace all matches, and not just the first one. Options are typically indicated including the slash, like “/g”, even though you do not add an extra slash, and even though you could use any non-word character instead of slashes.

What does S mean in Perl?

Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user. Syntax: s/text/pattern.


1 Answers

perl -pe's/\D*(\d+).*/$1/'

or

perl -nE'/\d+/&&say$&'

or

perl -nE'say/(\d+)/'

or

perl -ple's/\D//g'

or may be

perl -nE'$,=" ";say/\d+/g'
like image 108
Hynek -Pichi- Vychodil Avatar answered Oct 13 '22 05:10

Hynek -Pichi- Vychodil