Find the answer to your Linux question:
Results 1 to 3 of 3
Using printf and ed, or some other way, how would I replace a line that contains only a floating point number, e.g. 6.00, with another floating point number stored in ...
  1. #1
    Just Joined!
    Join Date
    May 2010
    Posts
    4

    Arrow Regular expressions (substituting floating point numbers)

    Using printf and ed, or some other way, how would I replace a line that contains only a floating point number, e.g. 6.00, with another floating point number stored in variable called $bulksize or $half ?

    I would like to identify the line by the line number.

    A related example:
    In this snippet:
    Code:
    bulksize=`expr 6.00`
    half=$(echo "scale=2; $bulksize / 2" | bc)
    for i in */run_example; do
    	printf '187s/= [^,]*/= %s/\nwq\n' "$bulksize" | ed -s "$i"
    	half=$(echo "scale=2; $half + 0.02" | bc)
    	bulksize=$(echo "scale=2; $half * 2" | bc)
    done
    The line
    Code:
    printf '187s/= [^,]*/= %s/\nwq\n' "$bulksize" | ed -s "$i"
    works for replacing the number in this line:
    Code:
      celldm(1)   = 6.00,
    Thanks for your help!

  2. #2
    Linux User
    Join Date
    Nov 2009
    Location
    France
    Posts
    292
    To me the problem is not clear enough as laid out. I understand you want to replace floating point values in a file, a sample of the target file would help. printf and ed may not be mandatory. , sed may well do the job.
    0 + 1 = 1 != 2 <> 3 != 4 ...
    Until the camel can pass though the eye of the needle.

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    Well, I have to give you credit for using ed. I don't think I've actually ever seen someone use it before.

    This will be easier to do by using sed, depending on how exactly we want to do this.

    If there's just a single floating point number on a line and we want to replace it, I would personally prefer to use sed. The sed command would be:
    Code:
    sed -re '187 s/[[:digit:]]\.[[:digit:]]/'"$bulksize"'/' "$i"
    There's a lot of weird quoting here, but it's necessary.

    Here, [[:digit:]]\.[[:digit:]] matches a floating point number, and this replaces it with bulksize on line 187.

    Now, if want to replace all of line 187 (maybe it's a lot more complicated, with multiple floating point numbers, or you just always want to change it to a certain line), you could do:
    Code:
    sed -e '187 c NEW_TEXT'
    People tend not to use ed these days because it's very complicated and weird. sed tends to be a bit cleaner.
    DISTRO=Arch
    Registered Linux User #388732

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...