annedroiid annedroiid - 4 months ago 4x
Bash Question

How do I add a string to the beginning of the name of a collection of files in another directory using shell

I have a bunch of .xml files in the folder project/reports. From the "project" folder, I need to prepend the string "TEST-" to every .xml file in the "reports" folder. I know each of the .xml files will start with the same string, and end with .xml, but I don't know the middle. How do I do this?

ie. Original file: constantfilename.xml, New file: TEST-constantfilename.xml

I can't hardcode the names of the test themselves, it just needs to be able to add the string to all files in the folder with the extension .xml. I have seen a lot of methods for renaming the files in the current folder like this:

for f in *.xml
mv "$f" "TEST-$f"

but I don't understand how I can apply this when I need to change them from another directory.

Any help would be greatly appreciated! And before anyone asks, no I cannot just navigate to that folder, it has to be from the "project" folder.


You could use the following one-liner (assuming you're on the project folder):

ls reports/*xml | awk -F '/' '{print "mv "$0" "$1"/TEST-"$2}' | sh

Is not as clean as yours, but it should give the same result.