0

Example of my text file:

03/Oct/2016:06:39:50-0500,cd/base/0/48/2.png,206,1514
03/Oct/2016:06:39:50-0500,cd/base/1/46/3.png,206,5796
03/Oct/2016:06:39:50-0500,cd/base/2/45/4.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/3/46/78.png,200,7208
03/Oct/2016:06:39:50-0500,cd/base/4/45/43.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/5/46/8.png,200,7208
...

In this text I must replace number after base/ following this rules:

if that_number=0 then that_number=5
if that_number=1 then that_number=6
if that_number=2 then that_number=7
if that_number=3 then that_number=8
if that_number=4 then that_number=9
if that_number=5 then that_number=10

Wanted result:

03/Oct/2016:06:39:50-0500,cd/base/5/48/2.png,206,1514
03/Oct/2016:06:39:50-0500,cd/base/6/46/3.png,206,5796
03/Oct/2016:06:39:50-0500,cd/base/7/45/4.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/8/46/78.png,200,7208
03/Oct/2016:06:39:50-0500,cd/base/9/45/43.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/10/46/8.png,200,7208

Any idea how can I do that?

  • if (0 <= that_number && that_number <= 5) that_number += 5 – Kaz Oct 25 '16 at 16:15
0

sed would work:

sed \
    -e 's/base\/1/base\/6/' \
    -e 's/base\/2/base\/7/' \
    -e 's/base\/3/base\/8/' \
    -e 's/base\/4/base\/9/' \
    -e 's/base\/5/base\/10/' \
    -e 's/base\/0/base\/5/'

I think you have to put the "base/0" case last, otherwise, the 5 -> 10 case kicks in as well.

  • 1
    It's also important (as you have done) to have the 5→10 case after the 1→6 case; otherwise, 5 will be replaced by 10 which will then be replaced by 60. – G-Man Oct 24 '16 at 21:40
4

In Perl it's easy to both match the context and do the addition:

perl -pe 's,base/\K\d+,$& + 5,e' input_file

We match anything of the form base/<numbers>, forget about the first part (up to the \K), and replace the rest with whatever was matched ($&) plus 5. e makes the replacement a Perl expression instead of just a string.

3

awk can make use of the fact that its a +5 operation on each number:

awk -F'/' '{$5+=5 ; print}' OFS='/' input_file

When using / as filed delimiter for input (-F'/') and output (OFS='/'), respectively, 5 needs to be added to field number 5.

Note that the slashes' positions and numbers are crucial here.

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.