1

I have a .txt file with bookmarks and all bookmarks above 100 have to be placed 2 pages down from where they are now, because I added two pages in the document. How do I write a bash script that adds 2 to all integers it finds in the document?

I'm new to writing code in general, but I already know that I should make a for loop to read each line, then determine if each word is an integer or not and then with an if statement add 2 to each integer above 100.

The problem is that i don't exactly know how to access (read and write) to the file and I also don't know how to determine if something is a number or not.

Here is the link to the .txt file. A small sample:

The Tortle Package; 24
    Tortle; 25
Elemental Evil Player's Companion; 27
    Aarakocra; 28
    Deep Gnome (gnome subrace); 30
Eberron\: Rising from the Last War; 84
    Changelings; 85
    Gnomes; 91
    Goblinoids; 92
        Bugbear; 93
        Goblin; 94
        Hobgoblin; 94
    Half-Elves; 94

I did some research and this is the code I've come up with:

#!/bin/bash
cd /home/dexterdy/Documents/
i=$(grep -ho '[0-9]*' bookmarks.txt)
if [ "$i" -gt 100 ]; then
    i += 2
fi

It seems that the grep variable outputs one large string with all the numbers. I also can't get the if-statement to work for some reason and I don't know how to actually write the numbers into the file.

Socowi
  • 25,550
  • 3
  • 32
  • 54

1 Answers1

2

From the shape of your input file, I suggest the following magic:

awk 'BEGIN{FS=OFS=";"}($NF>100){$NF+=2}1' input_file > output_file

This will remove that space just after the ;, which can be set back when doing:

awk 'BEGIN{FS=OFS=";"}($NF>100){$NF=" "($NF+2)}1' input_file > output_file

If you want to ensure that malformatted lines such as

foo;20
bar\; car;105

are all correctly converted into

foo; 20
bar\; car; 107

You have to do:

awk 'BEGIN{FS=OFS=";"}{$NF=" "($NF+($NF>100?2:0))}1' input_file > output_file
kvantour
  • 25,269
  • 4
  • 47
  • 72