Thursday, December 19, 2013

Unix/Linux - Shell script to find and replace a text from the list of files

Below is the automated shell script which will find a text and replace it with the given string. It will also keep a backup of existing file. It can also be used for global search and replace string from a text file. Please see the self-explanatory shell script below -

replace.sh

#!/bin/bash

#find string
searchString="text1"

#replace with
replaceWith="text2"

echo "searching "$searchString" ..."
grep -l $searchString * >foundIn.txt
chmod 777 foundIn.txt

echo "replacing "$replaceWith" ..."
count=0
while read x
do
  if [ $x != replace.sh ]
  then
          (cat  $x) >$x"_bkp"
          sed "s/${searchString}/${replaceWith}/g" $x"_bkp" >  $x
          count=$(($count+1))
          echo "Found in... "$x
  fi
done <foundIn.txt

echo $count "occurences have been replaced."

Linux/Unix - Shell script to read a text file

Method 1 - By iterating each line using while loop

#!/bin/bash

#Name of the text file
txtFile=myFile.txt

echo "Reading text file "$txtFile" ..."

while read x
do
echo $x
done <$txtFile


Method 2 - By using cat (concatenate and display files) command

#!/bin/bash

#Name of the text file
txtFile=myFile.txt

echo "Reading text file "$txtFile" ..."

cat $txtFile

Wednesday, December 18, 2013

keytool error: java.io.FileNotFoundException: cacerts (Permission denied)

I got the error when trying to install a certificate into my keystore

Command -
keytool -import -alias aliasName -file fileName.cer -keystore cacerts
keytool -list -keystore cacerts

Solutions

Windows -
This could happen if you are not running the command prompt in administrator mode. Login with the user who has administrator privilege.

For Windows 7 and above - Go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode.

For others windows -  Go to start -> all programs -> accessories -> right click command prompt and say run as administrator.

Linux -
First check the write permissions on the keystore. Also if needed login with root user and try the command.