Thursday, January 28, 2016

script to find and replace pattern in multiple files

There were set of files I wanted to update the class names including the file name. We were using the same pattern of class names for different svg files. This cause collision when multiple svg files were integrated to get the final output. The following was the script I used. 

The classes were starting as st0,st1,st2.... st<n>. I need to update these as <file_name>-st0, <file_name>-st1, <file_name>-st2... <file_name>-st<n>


#!/bin/bash

for file in $(find <directory> -type f -name '*.svg' | xargs grep -l '\.st0')
do
        base=$(basename $file .svg)
        name=$(  echo "$base" | sed -e 's/^\(.*\).V.*$/\1/' -e 's/\./ /g')
        sed -i -- "s/st[0-9]/$name-&/g" "$file"
done


The line #1
          for file in $(find <directory> -type f -name '*.svg' | xargs grep -l '\.st0')
search the list of file and iterate over the list.

The line #3
           base=$(basename $file .svg)
take the file base name excluding the extension.

The line #4
           name=$(  echo "$base" | sed -e 's/^\(.*\).V.*$/\1/' -e 's/\./ /g')
manipulates the string to replac using sed command.

And using the line #5, I am generating a temporary file with original content and replace the pattern.



To consolidate, the following is the outline of the program.

#!/bin/bash

for file in $(find <directory_to_search> -type f -name '<file type>' | xargs grep -l '<string_to_replace')
do
        replacement=<replacement_string>
        sed -i -- "s/st[0-9]/$replacement-&/g" "$file"
done




No comments:

Post a Comment