Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I would to grep certain parts of some shell command output in the shell script:

$ uname -r
>> 3.14.37-1-lts

Where I just need the 3.14.37.

And also for the shell script variable VERSION that has the value "-jwl35", I would like to take only the value "jwl35".

How can I use regular expression to this in shell script?

Thanks in advance!

share|improve this question

2 Answers 2

up vote 7 down vote accepted

Many, many ways. Here are a few:

  1. GNU Grep

    $ echo 3.14.37-1-lts | grep -oP '^[^-]*'
    3.14.37
    
  2. sed

    $ echo 3.14.37-1-lts | sed 's/^\([^-]*\).*/\1/'
    3.14.37
    
  3. Perl

    $ echo 3.14.37-1-lts | perl -lne '/^(.*?)-/ && print $1
    3.14.37
    

    or

    $ echo 3.14.37-1-lts | perl -lpe 's/^(.*?)-.*/$1/'
    3.14.37
    

    or

    $ echo 3.14.37-1-lts | perl -F- -lane 'print $F[0]'
    3.14.37
    
  4. awk

    $ echo 3.14.37-1-lts | awk -F- '{print $1}'
    3.14.37
    
  5. cut

    $ echo 3.14.37-1-lts | cut -d- -f1
    3.14.37
    
  6. Shell, even!

    $ echo 3.14.37-1-lts | while IFS=- read a b; do echo "$a"; done
    3.14.37
    
share|improve this answer
    
Thank you soooo much! –  Jialun Liu Mar 29 at 15:55
    
what is the purpose of "-oP" in "grep -oP" ? –  Abdul Al Hazred Mar 29 at 16:03
1  
@AbdulAlHazred, "-o" is for printing only the matching part and "-P" is to use the Perl regex pattern. You can check for "man grep" for details –  Jialun Liu Mar 29 at 16:09
    
ok , got it, so without -o the whole line is shown , with -o only the substring that matches it. –  Abdul Al Hazred Mar 29 at 18:29
1  
@AbdulAlHazred exactly. It's a neat way to only print the relevant parts of a line. –  terdon Mar 29 at 18:38

One approach not covered by terdon's comprehensive answer is Bash's parameter expansion (which requires no additional process):

vers=$(uname -r) && printf "%s\n" "${vers%%-*}"
3.14.37

vers="-jwl35" && printf "%s\n" "${vers#*-}"
jwl35
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.