0

In bash i have a string like this, please notice the first line and last line is blank.

How can i get the 300 number and the 20 number?

#first blank line

Found 300 modems:
/org/freedesktop/ModemManager1/Modem/20 [huawei] E3131
/org/freedesktop/ModemManager1/Modem/1 [huawei] E3131
/org/freedesktop/ModemManager1/Modem/0 [huawei] E303

#last blank line
1
  • Have you tried awk yet? Commented Apr 7, 2016 at 0:32

3 Answers 3

1

Here's a Perl version...

perl -ne 'if(m[Found (\d+)] || m[Modem/(\d+)]) {print "$1\n"}' < file_name

Note. You can use the following script top play with the regex...

#!/usr/bin/perl
use strict;
use warnings;

while(<DATA>) {
  if(m[Found (\d+)] || m[Modem/(\d+)]) {
    print "$1 \n";
  }
}
__DATA__
#first blank line

Found 300 modems:
/org/freedesktop/ModemManager1/Modem/20 [huawei] E3131
/org/freedesktop/ModemManager1/Modem/1 [huawei] E3131
/org/freedesktop/ModemManager1/Modem/0 [huawei] E303

#last blank line

If you save that script as test.pl you can use it like this...

perl -ne 'if(m[Found (\d+)] || m[Modem/(\d+)]) {print "$1\n"}' < test.pl

and I got the following output...

300
20
1
0
Sign up to request clarification or add additional context in comments.

Comments

0

If you have that output stored in a variable called ${var}, you can do

sed -n 's/Found \([0-9]*\) modems:/\1/p' <<< "${var}"

sed loops over all lines in the string, -n suppresses the output. If we find the line with Found n modems:, we substitute it with the number only (s command) and print the line (p flag).

4 Comments

I think he made it clear 300 and 20, your code only prints 300
Ah, yes, you're right. I leave that as an exercise. :-P
Oh i see, now that's one hell of excuse.
Can you please show me how to get the second number 20 please, thanks
0

This will print 300, 20, 1, and 0:

sed -ne 's/Found \(.*\) modems:/\1/p' -e 's:.*Modem/\([^ ]*\) .*:\1:p' FILENAME

-n says not to print the output by default
-e COMMAND executes COMMAND. You can use it more than once.
Ending the s command with p says to print if any substitution happens.

Run man sed for more information.

If you really only want 300 and 20 as output, append |head -2 to limit the output to the first two lines.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.