views:

63

answers:

1

i have following pattern

parts=/a,1mb,/b/c,2gb,/zee/last,-1 #general form on next line
^parts=path1,size1,...,lastPath,-1$

I want to replace all $path1,$size1 except $lastplace,-1 with $newPath,$newSize i.e.

parts_new=/p,2mb,/q/r,5gb,/zee/last,-1 #general on next line
^parts=newPathX,newSizeX,lastPath,-1$

I figured how to do it using at least one instance of ',' char as follows

sed 's|^parts=.*,\(.*,-1\)$|parts=newPathX,newSizeX,\1|gi'  

but what if parts has just one entry (the last one) how do I add newPathX,newSizeX before it? i.e.

parts=/zee/last,-1 :-> parts=/x/y,2mb,/zee/last,-1 # general on next
^parts=lastPath,-1$ :-> ^parts=newPathX,newSize,lastPath,-1$

i am thinking of grepping for two ',' first, and then conditionally replace it e.g.
wrote a quick conditional bash :

egrep -i '^parts=.*,.*,-1$' $file
if [[ $? -eq 0 ]] ; then
    sed 's|^parts=.*,\(.*,-1\)$|parts='$new',\1|gi' $inp
else
    sed -i -e 's|^parts=|parts='$new',_gi' $file
fi

I wonder if its possible to do both in one go using sed ?
Okay awk will do, but what if I just have empty 'parts=' line? i.e.

parts= :-> parts=newPathX,newSizeX,lastPath,-1

sed appreciated as I can quickly understand it (but awk will do too ! )

A: 

use awk

$ var='puthere=$place1,$size1,$place2,$size2,(..and so on..),$lastplace,-1'
$ echo "$var" | awk -F"[=,]" -vnp="$newplace" -vns="$newsize" '/puthere/{print "puthere="np,ns,$(NF-1),$NF}' OFS=","
puthere=test1,size1,$lastplace,-1
ghostdog74
thank you very much for the nice 'awk' script, guess i'll have to start digging awk now :) But will it be too much to ask for single line sed magic ?Thanks again !
Prince
I ask because the pattern comes as a line in a text file, can someone tell me how to convert above into something that will take $1=filename as argument and do the rest ?
Prince
there are times when things can be done simpler by not using sed.
ghostdog74
hmm, I think I better customize your awk solution to my bash script, looks quite elegant :) I give up on sed :( !
Prince