Main BLOGGER
Google
WWW THIS BLOG
Monday, March 19, 2007
 
Search strings in the file and create new files by replacement
#!/bin/bash

ARGS=5         # Script requires 3 arguments.
E_BADARGS=65   # Wrong number of arguments passed to script.

if [ $# -lt "$ARGS" ]
# Test number of arguments to script (always a good idea).
then
  echo "Usage: `basename $0` directory old-pattern new-pattern"
  echo "Find all text files under directory recursively and replace old-pattern with new-pattern,
        output files are stored in current directory"
  exit $E_BADARGS
fi

if [ -d "$1" ]
then
    directory=$1
else
    echo "Path \"$1\" does not exist."
    exit $E_BADARGS
fi

for file in $( find $directory -type f -name '*' -exec grep -l "$2\|$4" {} \; | sort )
# find all files which include the pattern strings $2 and $4
do
  new_path=`dirname $file`
  mkdir -p ./$new_path
  new_file=./$file 
#  n1=`grep $2 $file | wc -l`
#  n2=`grep $4 $file | wc -l`
#  if [ $n1 -gt 0 ] || [ $n2 -gt 0 ]
#  then
     echo $file
     sed -e "s_$2_$3_g" $file | sed -e "s_$4_$5_g" > $new_file
     # replace the first pattern $2, then $4
#  fi
done 
  
echo "All Done. Check results in current directory"

exit 0

--
Pop (Pu Liu)



<< Home

Powered by Blogger

Google
WWW THIS BLOG