Issue
I'm trying to write a bash script to change an xml file name and contents within this XML file for over 500 different folders.
I'd prefer to use the sed
command for this process with a bash script instead of using xmlstarlet
as I don't want to install it on this VM. The directory is a little annoying as the xml file is the same name as a previous directory.
This is an example of a file to be modified:
/var/opt/FTPserver/users/MainUsers/junk/VFS/junk.xml
^^^^ ^^^^
With junk.xml
containing a line:
<url>file://home/FTPserver/Customer/junk/</url>
^^^^
I would like to rename the file to the following:
/var/opt/FTPserver/users/MainUsers/junk/VFS/treasure.xml
^^^^ ^^^^^^^^
With junk.xml
containing the modified line:
<url>file://home/FTPserver/Customer/treasure/</url>
^^^^^^^^
The customerlogin.csv
is comma delimited with column A = junk
and column B = treasure
as my test example.
while IFS=, read -r orig new; do
find "/var/opt/FTPserver/users/MainUsers/"$orig"/VFS/" -name "$orig" -execdir mv -n -- {} "$new" \;
sed -i 's#/"$org"#$new"#' "$new".xml
done < customerlogin.csv
I'm new to bash and scripting. I expect I can't reference the .xml file like above and nothing occurs when I run the script.
Solution
Try this as a starting point at least:
dir='/var/opt/FTPserver/users/MainUsers/'
while IFS=, read -r oldStr newStr; do
oldFile="$dir/$oldStr/VFS/${oldStr}.xml"
newFile="$dir/$oldStr/VFS/${newStr}.xml"
if [[ -f "$oldFile" ]] && [[ ! -f "$newFile" ]]; then
sed "s:/$oldStr/:/$newStr/:" "$oldFile" > "$newFile" &&
rm -f "$oldFile"
fi
done < customerlogin.csv
That assumes your oldStr
and newStr
strings dont' contain regexp metachars or backreference metachars, see Is it possible to escape regex metacharacters reliably with sed, and that oldStr
only occurs in the location where you want to change it in the files.
Answered By - Ed Morton Answer Checked By - David Goodson (WPSolving Volunteer)