Well, here's a wikipedia page for matching or replacing with Perl one liners. I did this in Cygwin:
Perl can behave like grep or like sed.
The /s
makes dot match new line.
The -0777
makes it apply the regular expression to the whole thing instead of line by line.
\n
can match new line as well.
$ echo -e 'a\nb\nc\nd' | perl -0777 -pe 's/.*c//s'
d
user@comp ~
$ echo -e 'a\nb\nc\nd' | perl -pe 's/.*c//s'
a
b
d
Here is the other form, -ne
with print $1
:
user@comp ~
$ echo -e 'a\nb\nc\nd' | perl -ne 'print $1 if /(.*c)/s'
c
user@comp ~
$ echo -e 'a\nb\nc\nd' | perl -0777 -ne 'print $1 if /(.*c)/s'
a
b
c
user@comp ~
$
Also
$ echo xxx|perl -lne 'print ""'
Perl's equivalent of \0 or &, i.e. the whole match is $_ or to be able to put text before and after without a space, ${_}
$ echo xxx|perl -lne 'print "a${_}${_}a"'
axxxxxxa
and
$ echo xxx|perl -lpe 's/.*/a${_}${_}a"/'
axxxxxxa"
###Some further examples
$ cat t.t
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
$ perl -0777 -ne 'print $1 if /\<ul\>(.*?)\<\/ul>/s' t.t
<li>item 1</li>
<li>item 2</li>
user@comp ~
$ perl -0777 -ne 'print $1 if /(.*)/s' t.t
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
user@comp ~
$
An example of Global for the -ne
one (change "if" to "while"):
$ echo -e 'bbb' | perl -0777 -ne 'print $1 while /(b)/sg'
bbb
For the -pe
one, just add the g
at the end (/sg
or /gs
, same thing):
$ echo -e 'aaa' | perl -0777 -pe 's/a/z/s'
zaa
user@comp ~
$ echo -e 'aaa' | perl -0777 -pe 's/a/z/sg'
zzz
Note- This question contrasts /s and -0777
Those print $1
examples don't show the whole line. this link https://dzone.com/articles/perl-as-a-better-grep has this example that does perl -wln -e "/RE/ and print;" foo.txt
Best Answer
Depending of what is a "word" for you, you can use:
\S+(?=\h+\S+$)
will match 1 or more not space followed by 1 or more horizontal space then 1 or more non space[a-zA-Z]+(?=\h+[a-zA-Z]+$)
[a-zA-Z0-9]+(?=\h+[a-zA-Z0-9]+$)
\pL+(?=\h+\pL+$)
[\pL\pN]+(?=\h+[\pL\pN]+$)