tags:

views:

23

answers:

2

I have a Korn shell script that I would like to change a variable based on another and a regex.

What I want to happen is to generate a variable value like below, but without calling sed:

$ echo 'orl,bdl,lap' | sed "s/,*orl//" | sed "s/^,*//"   
bdl,lap  
$ echo 'orl,bdl,lap' | sed "s/,*bdl//" | sed "s/^,*//"  
orl,lap  
$ echo 'orl,bdl,lap' | sed "s/,*lap//" | sed "s/^,*//"  
orl,bdl    

I've tried variations of

export b="orl,bdl,lap"  
export a=${b}*(,*lap)    

but usually get an error. Is this possible?

I've seen this:

if [[ $var = fo@(?4*67).c ]];then ...  

so it should work like it does with filenames.

+1  A: 

Is it something like this?

echo 'orl,bdl,lap' | cut -d"," -f3,2

Change the -f3,2 to other fields that you may need.

Also if you need better regex construction you could use awk, but then I need you provide better details to understand what transformation you need.

jyzuz
I would normally pipe out into sed or awk but I came across a note saying that you could do the regex internally and wanted to learn it.
jim
A: 

One way to do this is to use IFS:

var='orl,bdl,lap'
saveIFS=$IFS
IFS=','
array=($var)
newvar="${array[*]:1}"
IFS=$saveIFS

or

var='orl,bdl,lap'
saveIFS=$IFS
IFS=','
set -- $var
shift
newvar="$*"
IFS=$saveIFS

Or using regex matching:

var='orl,bdl,lap'
pattern='^[^,]*,(.*)$'
[[ $var =~ $pattern ]]
newvar=${.sh.match[1]}
Dennis Williamson
Cool - just the nudge i needed.
jim