Operating System - HP-UX
1748130 Members
3659 Online
108758 Solutions
New Discussion

Re: change character , when a string occurs ( possible one liner )

 
SOLVED
Go to solution
support_billa
Valued Contributor

change character , when a string occurs ( possible one liner )

hello,

 

i want to remove a string in a variable only when variable occurs  like "/dev" .

maybe the input for a variable include "/dev/vgname" or only "vgname".

 

vg_name=/dev/vgname"

..

vg_name=$( echo  "${vg_name}" | sed "s|^/dev/||g" )

 

or it is better to do every time ?

 

is ksh command like "${parameter#pattern}" an option ?

i only know a check like  if [ $( echo "${vg_name}" |grep "^/dev" > /dev/null ; echo $? ) -eq 0 ] ..

 

[ $( echo "${vg_name}" |grep "^/dev" > /dev/null ; echo $? ) -eq 0 ] && sed ....

 

regards

4 REPLIES 4
James R. Ferguson
Acclaimed Contributor

Re: change character , when a string occurs ( possible one liner )

Hi:

 

As always, TMTOWTDI.

 

For pure efficiency, I'd use the shell:

 

$ vg_name=/dev/vg99
$ echo ${vg_name##*/}
vg99

$ vg_name=vg88
$ echo ${vg_name##*/}
vg88

 Regards!

 

...JRF...

Doug O'Leary
Honored Contributor
Solution

Re: change character , when a string occurs ( possible one liner )

Hey;

 

The previous post got it, but just for completeness:

 

Var="Abc/Def/Ghi"

echo ${Var#*/}   = Def/Ghi

echo ${Var##*/} = Ghi

 

One hash is the shortest possible match from the beginning of the string; Two hashes is the biggest possible match.

 

A similar thing can be done from the other side of the string:

 

echo ${Var%/*}     = Abc/Def

echo ${Var%%/*} = Abc

 

You need 2 hashes in your case because one hash would only match the first '/':

 

Vg=/dev/vg01

echo ${Vg#*/} = dev/vg01

echo ${Vg##*/} = vg01

 

Those are really useful constructs; I use them in my scripts quite a bit.

 

Hope that helps.

 

Doug O'Leary


------
Senior UNIX Admin
O'Leary Computers Inc
linkedin: http://www.linkedin.com/dkoleary
Resume: http://www.olearycomputers.com/resume.html
support_billa
Valued Contributor

Re: change character , when a string occurs ( possible one liner )

thx ,

last question :

how can i detect , if in a string is maybe "/dev" , maybe in a "if" statement

 

only so

[ $( echo "${vg_name}" |grep "^/dev" > /dev/null ; echo $? ) -eq 0 ] && sed ....

Doug O'Leary
Honored Contributor

Re: change character , when a string occurs ( possible one liner )

Hey;

 

>>how can i detect , if in a string is maybe "/dev" ,

 

"grep -q" is really useful for that:

 

echo "${var}" | grep -qi "/dev" && echo "${var} has /dev in it" || echo "${var} is missing /dev"

 

HTH;

 

Doug


------
Senior UNIX Admin
O'Leary Computers Inc
linkedin: http://www.linkedin.com/dkoleary
Resume: http://www.olearycomputers.com/resume.html