1

I have a text file which contain only 1 line of text

1314:Battery:1.90:50:30

I'm trying to figure out if is there anyway to do a grep and sed to change the value 50 and 30 to the following

1314:Battery:1.90:45:35

which I would reduce 5 from 50 and increase 5 from 30.

Please guide me if there is a better way to solve this problem ? I just started picking up this scripting. Thanks =)

3

With perl:

perl -i -F: -lape '$F[3]-=5;$F[4]+=5;$_=join ":",@F' the-file

With sh (assuming those numbers are always decimal integers without leading zeros):

IFS=: read -r a b c d e < the-file &&
  printf '%s\n' "$a:$b:$c:$((d-5)):$((e+5))" > the-file

With recent versions of GNU awk:

gawk -i inplace -F: -vOFS=: '{$4-=5;$5+=5}1' the-file
6
awk -F":" '{OFS=":"; print $1,$2,$3,$4-5,$5+5}' filename

Output:

1314:Battery:1.90:45:35
  • 1
    This works good. You could also use printf with the format if you do not want to use OFS. – unxnut Jan 7 '15 at 15:57

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.