Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed conditional replace of a variable

Tags:

regex

sed

I have within a file a bunch of codenumbers that in general are of the form, integer.integer The first integer is necessary, the second may be empty. e.g. 123.45 or 12.345 and 12 are all valid codenumbers.

I want to use sed to change each of these lines into

job{123}subjob{45}
job{12}subjob{345}
job{12}  

So far I have

sed -e 's/codenumber{\([0-9]*\)\.*\([0-9]*\)}/job{\1}subjob{\2}/g'

which results in

job{123}subjob{45}
job{12}subjob{345}
job{12}subjob{}

Is there a way for sed to realise that when the variable \2 is empty, to print a default value instead, say 0. Hence the last line of the given example would say

job{12}subjob{0}

I suppose this could be possible via two sed runs, but I am interested if it was possible with one.

like image 670
Geoff Avatar asked Jan 28 '26 01:01

Geoff


2 Answers

You could simply extend your sed command to patch up empty subjob numbers:

sed -e 's/codenumber{\([0-9]*\)\.*\([0-9]*\)}/job{\1}subjob{\2}/g' \
    -e 's/subjob{}/subjob{0}/g'
like image 120
Jonathan Leffler Avatar answered Jan 31 '26 01:01

Jonathan Leffler


I don't think this is possible in sed. But indeed you can do two sed runs (they're really fast so it shouldn't be a problem), the second being

sed -e 's/subjob\{\}//g'
like image 40
alestanis Avatar answered Jan 31 '26 01:01

alestanis