File Copy – How to Rename Files While Copying

bashfile-copyrenameshell

How would I copy (archive style where date isn't changed) all the files in a backup directory to the user's directory while renaming each file to remove the random string portion from the name (i.e., -2b0fd460_1426b77b1ee_-7b8e)?

cp from:

/backup/path/data/Erp.2014.02.16_16.57.03-2b0fd460_1426b77b1ee_-7b8e.etf

to:

/home/user/data/Erp.2014.02.16_16.57.03.etf

Each file will always start with "Erp." followed by the date-time stamp string followed by the random string and then the extension ".etf". I want to keep all name elements including the date-time stamp. I just want to remove the random string.

The random string allows multiple backups of the same file. However, in this case, I just ran fdupes and there are no duplicates. So I can simply restore all the files, removing the random string.

I'm looking for a one-line bash command to do it.

If that won't work, I could do it in two or more steps. I normally use KRename, but in this case I need to do it in bash. (I'm working remotely.)

Best Answer

pax can do this all at once. You could do:

cd /backup/path/data && pax -wrs'/-.*$/.etf/' Erp*etf /home/user/data

pax preserves times by default, but can add -pe to preserve everything (best done as root) or -pp to preserve permissions , eg:

cd /backup/path/data && pax -wrs'/-.*$/.etf/' -pe Erp*etf /home/user/data

Otherwise (pax isn't usually available by default), surely it is better to do a copy then a rename:

cp -a /backup/path/data/Erp*.etf /home/user/data
rename 's/-.*$/.etf/' /home/user/data/Erp*.etf

This way there is not a different process started for each file.

Related Question