rename - How to use a csv file with oldvalue:newvalue to replace string inside files and filenames -
we have large number of rules files carry 1 of >200 phonenumbers in filename and/or reference phonenumber in file itself.
of these phonenumbers need changed have input csv file has column old phonenumber , column phonenumber.
additional complication, there comments inside files contain phonenumber, spaces in right places, e.g. 0800 123 456.
phonenumbers in csv file spaces in comments.
what want achieve write (shell) script reads csv file , replaces occurences of old phonenumber inside files (with , without spaces) new phonenumber (again spaces in comments , without spaces in other places). additionally, if file found has phonenumber in filename, should renamed.
i'm sure can done sed , similar tools i'm lacking experience sed.
i able find solution myself. it's not beautiful , far being efficient job. preconditions input file lines in following format:
<old string>;<new string>
the "old string" in case phone number in format
012 345 67 89
the reason having number whitespace have in comment in each file need replace both types.
here's bash script assuming want scan files in subdirectory "src" , input file named "bns.csv":
#!/bin/bash while read line old=`echo $line | awk -f\; '{print $1}'` ## remove leading , trailing spaces oldtrim="$(echo -e "${old}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" new="$(echo $line | awk -f\; '{print $2}')" newtrim="$(echo -e "${new}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" # remove spaces oldpure="$(echo -e "${old}" | tr -d '[[:space:]]')" newpure="$(echo -e "${new}" | tr -d '[[:space:]]')" # rename files first find src -exec rename ${oldpure} ${newpure} {} \; #find , replace both versions inside file find src -type f | while read file sed -i "s/${oldtrim}/${newtrim}/g" $file sed -i "s/${oldpure}/${newpure}/g" $file done done <bns.csv
any optimization hints welcome.
Comments
Post a Comment