Home > Software engineering >  modify a digit of string in a file line by arithmetic
modify a digit of string in a file line by arithmetic

Time:10-19

On a clearly specific line of my file, for example let's say Line 93, I have a coordinate of 3 components in the range [0.0, 1.0). I want to add the first and the second number by 0.5 or -0.5, making it still in the range [0.0, 1.0), while leaving the third number unchanged. How can I write a script to do this through sed or awk or anything else? There's a batch of files to be processed, thanks a lot for help.

Input:

...
  0.6004778515530910  0.3354932652277851  0.0828914297825582
...

Output:

...
  0.1004778515530910  0.8354932652277851  0.0828914297825582
...

ps: Another feature is that the tenths digit of the first number is always the 5th of the string (there are two spaces at the front), and the second is always the 25th. I'm not sure whether this will make the task easier.

CodePudding user response:

 echo '  0.6004778515530910  0.3354932652277851  0.0828914297825582' |
mawk '$!NF=sprintf("\n\t%s\n\t%.*s%.f%.*s%d%s", $(_<_),
      _ =_ =_^=_<_,$!_,(  _ substr($!_,_,!!_)) %(_ _),_*_-  _,
      substr($!_,_),(substr($!_,--_*_,!!_) _) %(_ _),
                     substr($!_,_*_ (_^=!_)))'
      0.6004778515530910  0.3354932652277851  0.0828914297825582
      0.1004778515530910  0.8354932652277851  0.0828914297825582

CodePudding user response:

With GNU awk:

$ awk -v CONVFMT='%.16f' '{$1 =($1<0.5)?0.5:-0.5; $2 =($2<0.5)?0.5:-0.5; print}' file
0.1004778515530910 0.8354932652277851 0.0828914297825582

Explanation: The CONVFMT GNU awk variable specifies the conversion format for numbers; %.16f means 16 digits after the radix character.

$1 =($1<0.5)?0.5:-0.5 adds 0.5 to the first field it is less than 0.5, else it subtracts 0.5. $2 =($2<0.5)?0.5:-0.5 does the same for the second field. And print prints the modified record.

If you want to keep the 2 leading spaces use print " " $0 instead of just print:

$ awk -v CONVFMT='%.16f' '{$1 =($1<0.5)?0.5:-0.5; $2 =($2<0.5)?0.5:-0.5; print "  " $0}' foo.txt 
  0.1004778515530910 0.8354932652277851 0.0828914297825582
  •  Tags:  
  • bash
  • Related