2

I've created a script which writes .flame/XML-like files, containing within them, a string which looks like:

scale="n"

where n is a random number, with a variable number of digits. What I am attempting to do is replace this string with another random number within a particular range; generating this number is trivial, as I already have shuf working for this purpose. The trouble arises when attempting to find and replace this string, as it could be similar to any of the following:

scale="54.1948", scale="182.55816", or scale="3.59"

I've tried using sed for this, and while I'm confident it's possible, I have not found the correct syntax. The occurrence of this string is not consistent between files.

Ideally, the command I am looking for would convert a string which looks like this:

scale="54.1948" or scale="3.59"

to one which looks like:

scale"254" or scale="579"

Thanks for any help.

  • 1
    Is the file in fact an XML file? In that case one could possibly do it with XMLstarlet. – Kusalananda Jan 4 '17 at 11:52
3

The syntax you are looking for is sed -e 's/\(scale=\)"[0-9]\+\(\.[0-9]\+\)\?"/\1"'"$replacement_number"'"/'. The search regex in detail:

\(scale=\)        the literal string scale=, remembered as \1
"                 opening double quote
[0-9]\+           one or more digits
\(\.[0-9]\+\)\?   optionally, a period followed by one or more digits
"                 closing double quote
0

This is a simpler and more generalized solution. Extended sed syntax (-e) and back-references are not used for this solution.

This replaces everything between the double quotes with the number $n.

The basic sed command looks like this:

s/scale="[^"]*"/scale="$n"/

The expression [^"]* matches zero or more non-double-quote characters. After quoting, the shell command looks like this:

sed "s/scale=\"[^\"]*\"/scale=\"$n\"/"

If you want to change only the scale values which contain numbers and decimal points only, you could use someting like this:

s/scale="[.0-9]*"/scale="'$n"/

There's usually a trade off between input checking vs readability and maintainability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.