Fornax-A
Fornax-A

Reputation: 1032

change a single word in a file with Bash

i try to write a very simple bash file that allow my to open and modify n times a file.java .

The modification i want is only a change in a single (or two) row of a single number.

I try to do this with the follow code:

    #!/bin/bash

    # commento

    touch ic.java

    touch input

    n=0
    for n in "1" "2" "3" "4.5"
  do
        echo 'import java.io.*;'>ic.java
        echo 'import java.util.*;'>>ic.java
        echo ' '>>ic.java
        echo 'class INITIAL_CONDITION_NORMAL {'>>ic.java
        echo 'public static void main (String args[]) {'>>ic.java
        echo "$n">>ic.java 
        n=$(($n+1))
        echo '....'>>ic.java 
 done 

       java ic.java

as you see i must write all the file and, when i like to change the number, put the "$n" and n=$(($n+1)) in the row then go on until the end of the file and lounch it (java ic.java).

I know i can use something like:

sed -i 'm-th_row/old/new/' ic.java

but if i want to do this recursively (100 times) whit every time a different new value (as in the example) how can i do that?

Thanks a lot for Your help !

Upvotes: 1

Views: 100

Answers (1)

ams
ams

Reputation: 25579

As long as new contains no / (slash) character, or any other special character that would confuse sed, this is the sort of pattern you need.

for n in "1" "2" "3" "4.5"
  sed -i "m-th_row/old/$n/" ic.java
done

Of course, that snippet would just modify the same file repeatedly, which probably wouldn't be helpful, but you get the idea.

Upvotes: 1

Related Questions