开发者

Editing a comma-separated list of path,size pairs

I have lines of the form

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 so that it looks like

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 this breaks if the list only has the last path and size. For example, I want

parts=lastPath,-1

to be transformed to

parts=newPathX,newSize,lastPath,-1

So I tried to fix this with a conditional in 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 would like to know a pure sed solution as I can quickly understand i开发者_运维问答t, but awk will do too.


Try using 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


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

Sometimes, its also very simple in sed ;-). Just add a filter before to avoid your exception case

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜