Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple charcter using regex substitution

Tags:

regex

perl

I am trying to perform a regex substitution on the output of acpi command. My perl one liner for this is:

acpi | perl -F/,/ -alne 'print $F[1] if ($F[1]=~s!\s|%!!)'

The output of the above one liner is 87% whereas my required output is just 87 so it is not replacing % in the string.

Now the output of acpi command is

Battery 0: Discharging, 87%, 05:54:56 remaining

and the output of print $F[1] is

ronnie@ronnie:~$  acpi | perl -F/,/ -alne 'print $F[1]'
 87%   #space followed by 87%#
ronnie@ronnie:~$ 

Now the strange this is if I try the same perl one-liner on:

echo " 86%" | perl -nle 'print if s!\s|%!!g'

It works fine and outputs 86.

So, why it is not working with acpi command.

PS: I am aware this can be achieved by using sed/awk but I am interested why my solution is not working.

like image 365
ronnie Avatar asked Jul 28 '26 13:07

ronnie


2 Answers

Your one-liner does not work as you expect because

s!\s|%!!

replaces either a whitespace or a percent sign, not both.

If you want it to replace both, add the global /g modifier:

s!\s|%!!g

Just as you coincidentally did in your other example.

You might also consider using a character class instead of alternator:

s![\s%]!!g

If your output follows the format you showed, you might be better off using a simple regex:

echo Battery 0: Discharging, 87%, 05:54:56 remaining|perl -nlwe 'print /(\d+)%/'
87
like image 85
TLP Avatar answered Jul 31 '26 04:07

TLP


This one works as expected:

echo " 86%" | perl -F/,/ -alne 'print $F[1] if ($F[1]=~s!\s*(\d+)%!$1!)'
like image 33
perreal Avatar answered Jul 31 '26 03:07

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!