rblog

Shell script looping files in a directory, search and replace text in each file

Had to create a shell script that is looping through a set of XML files in a given directory. For each file it checks if the file has the attribute “CCSID“. It it does not have the attribute, it inserts the attribute just after the opening tag MQQueueConnectionFactory using Perl, and if it is there already it will update the value using a SED-command with a simple REGEX-pattern. Ok, I know that I could have used either SED or Perl for both, but I just borrowed from some other scripts I had, so that is the reason.

The REGEX-pattern ain’t no rocket science, but since I use REGEX only once in a while I find it quite hard to crate patterns, could not have done it without http://www.gskinner.com/RegExr/

  FILES=/path_to_directory/my-files*.xml
  for file in $FILES
  do
    # CCSID attribute present or not
    grep CCSID $file  >> /dev/null
    if [ $? -eq 1 ]
    then
      # Not present, insert
      perl -pi -e "s#<MQQueueConnectionFactory\s#<MQQueueConnectionFactory CCSID=\"1208\" #g" ${file}
    else
      # Present, update
      sed -i 's/CCSID="[0-9]*"/CCSID="1208"/' ${file}
    fi
  done