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
The highlighting in TTY1 works since it sets the TERM variable to a proper value.
If you're using screen:
Change the TERM variable to a proper value (e.g., screen or screen-256color). Check your personal ~/.screenrc or the system-wide /etc/screenrc and fix the corresponding line.
In my version of less, the value screen-256 should actually results in an error:
WARNING: terminal is not fully functional
- (press RETURN)
If you're not using screen:
The screen* only get interpreted correctly by screen.
The correct value for TERM depends on your terminal emulator and should usually get set by it. The default of Ubuntu's three pre-installed terminal emulators is xterm.
Execute
grep -R TERM= ~/.* /etc 2> /dev/null
the check if TERM's value gets overridden in your shell's configuration files.
Best Answer
You can do:
The pattern replacing
pattern
, but the$
must stay, it tells the search to look for the pattern, and then the end of the line.So you'd do: