script to search and edit scripts

Hi all,
can you please help me in this one..

i have a many scripts in a directory & i get many requests to change the code of a particular script.

for example file abc.txt contains
#!/bin/bash
mumbai 102403445
chennai 123980123
delhi 3456268468
kolkata 465376832
#kolkat 462945959

i get a request to change the value ( population of kolkata ) 46852342424

my script should to

#!/bin/bash
mumbai 102403445
chennai 123980123
delhi 3456268468
#kolkata 465376832 # i have to keep old entry as comment
kolkata 4685234242
#kolkata 462945959

so my script should search for KOLKATA and keep old entry as comment and change it to new value. please help me..

>fixabc kolkata 468523424

SCRIPT fixabc
findrec=$1
newval=$2
old=$(cat abc.txt | grep "^"$findrec)

grep -v "^"$findrec abc.txt >abc2.txt
echo "#"$old >>abc2.txt
echo $findrec" "$newval >>abc2.txt

>>>NOTES
first couple lines takes input
reads/finds existing line
uses grep to copy everything except
writes the old line begin with #
writes the new line
AND the "^" is an anchor to read from the first column/character in a line

I would recommend you don't put #!/bin/bash at the start of a text file like that unless you are ok with calling those placenames as commands.

If you want it to leave the order of the file intact, try this:

#!/bin/sh
while read line
do
  if echo $line | egrep "^$1" > /dev/null
  then
    # We have found our line
    echo "#$line"
    echo "$1 $2"
  else
    echo $line
  fi
done

usage: scriptname.sh kolkata 46852342424 < inputfile.txt > outputfile.txt

thanks a lot, your code works perfectly!!:slight_smile: