Unix questions - awk regular expression to extract string between two characters of variable

This is Interesting: Free IT Magazines  
Home > Archive > Unix questions > February 2006 > awk regular expression to extract string between two characters of variable





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author awk regular expression to extract string between two characters of variable
jason@cyberpine.com

2006-02-07, 6:03 pm

without using basename and cut.. how can extract the string between "_"
and ".sh", in this case "myfile" without greedy using awk egrep and/or
regular expressions..

x=/a/b/c/05.00/x_y/222_myfile.sh

would like y=myfile in the above example.

Many thanks in Advance for any help or information!

Stephane CHAZELAS

2006-02-07, 6:03 pm

2006-02-7, 12:27(-08), jason@cyberpine.com:
> without using basename and cut.. how can extract the string between "_"
> and ".sh", in this case "myfile" without greedy using awk egrep and/or
> regular expressions..
>
> x=/a/b/c/05.00/x_y/222_myfile.sh
>
> would like y=myfile in the above example.
>
> Many thanks in Advance for any help or information!


y=$(expr "x$x" : '.*_\([^/]*\)\.sh$')

or

y=$(expr "x$x" : '.*_\([^/_]*\)\.sh$')

depending on what you want.

--
Stéphane
Chris F.A. Johnson

2006-02-07, 6:03 pm

On 2006-02-07, jason@cyberpine.com wrote:
> without using basename and cut.. how can extract the string between "_"
> and ".sh", in this case "myfile" without greedy using awk egrep and/or
> regular expressions..
>
> x=/a/b/c/05.00/x_y/222_myfile.sh
>
> would like y=myfile in the above example.


In a POSIX shell:

y=${x%.sh} ## y=/a/b/c/05.00/x_y/222_myfile
y=${y##*_} ## y=myfile

--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
Stephane CHAZELAS

2006-02-07, 6:03 pm

2006-02-7, 16:01(-05), Chris F.A. Johnson:
> On 2006-02-07, jason@cyberpine.com wrote:
>
> In a POSIX shell:
>
> y=${x%.sh} ## y=/a/b/c/05.00/x_y/222_myfile
> y=${y##*_} ## y=myfile


As long as $x has the expected format.

If it may not, then you need something like:

case ${x##*/} in
*_*.sh)
y=${x%.sh}
y=${y##*/}
y=${y#*_}
true
;;
*)
y=
false
;;
esac

--
Stéphane
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com