sed command find and replace in file and overwrite file , how to initialize file has current file/script

1.1k views Asked by At

I wanted to increment the current decimal variable, so I made the following code

#! /bin/bash
k=1.3
file=/home/script.sh
next_k=$(echo "$k + 0.1" | bc -l)
sed -i "s/$k/$next_k/g" "$file"
echo $k

As you can see here I have to specify the file in line 3 , is there a workaround to just tell it to edit and replace in the current file. Instead of me pointing it to the file. Thank you.

1

There are 1 answers

0
zzevannn On BEST ANSWER

I think you're asking how to reference the own script name, which $0 holds, e.g.

#! /bin/bash
k=1.3
next_k=$(echo "$k + 0.1" | bc -l)
sed -i "s/$k/$next_k/g" "$0"
echo $k

You can read more on Positional Parameters here, specifically this bit:

($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Shell Scripts), $0 is set to the name of that file. If Bash is started with the -c option (see Invoking Bash), then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.

e.g.

$ cat test.sh
 #! /bin/bash
 k=1.3
 next_k=$(echo "$k + 0.1" | bc -l)
 sed -i "s/$k/$next_k/g" $0
 echo $k
$ ./test.sh; ./test.sh ; ./test.sh
 1.3
 1.4
 1.5
$ cat test.sh
 #! /bin/bash
 k=1.6
 next_k=$(echo "$k + 0.1" | bc -l)
 sed -i "s/$k/$next_k/g" $0
 echo $k