Find number in string and replace it

1

1

I wrote C++ code and now I want to replace the number in a string by using shell scripts.

The part that needs to be replaced:

if (random<=90)

How I can change the 90 from a shell script?

I wrote this but I need something efficient other than sed or with a better regular expression just to match the number itself.

for i in {1..1000..100}
do
sed -i "s/(random<=.*)/(random<=$i)/g" myfile
done

Arash

Posted 2013-12-12T20:55:12.033

Reputation: 678

@slhck i working with NS3 and ns3 is linux based simulator that use C++ file to build network. and every time i need o change some network parameter i need to change the c++ file(edit was made for question) – Arash – 2013-12-12T21:20:00.050

by the way i think this is not XY problem because the C++ file is just for building the results not for calculation and all af calculations done with shell scripting. could you plz help me with this? – Arash – 2013-12-12T21:24:23.147

1I know NS3. I think it'd be easier if you could just pass arguments to the C++ file instead. Anyway… what is the real question? Your script works, doesn't it? The only thing wrong with it is that it will always overwrite myfile until you end up with random<=901 at the last iteration. – slhck – 2013-12-12T21:25:43.810

@slhck how could i replace just number? and what tool do you offer to me – Arash – 2013-12-12T21:26:48.763

Answers

2

If you just want to match the number, you need positive lookbehind and lookahead. sed does not support this, but perl does.

perl -pi -e "s/(?<=\(random<=).*(?=\))/$i/g" myfile

To explain:

(?<=                         positive lookbehind
  \(random<=                 match a literal (random<=
)
.*                           match any character, multiple times
(?=                          positive lookeahead
  \)                         match a literal )
)

The lookbehind and lookahead matches are not used, so you can replace with $i.

slhck

Posted 2013-12-12T20:55:12.033

Reputation: 182 472

i think you are the father of linux :) – Arash – 2013-12-12T21:35:10.490

Problem solved! – Arash – 2013-12-12T22:08:27.770