Emile
Emile

Reputation: 185

How can I move multiple files to a directory while changing their names and extensions using bash?

There are multiple files in /opt/dir/ABC/ named allfile_123-abc allfile_123-def allfile_123-ghi allfile_123-xxx.

I need the files to be named new_name-abc.pgp new_name-def.pgp new_name-ghi.pgp new_name-xxx.pgp and then moved to /usr/tst/output

for file in /opt/dir/ABC/allfile_123* ; 
do mv $file /usr/tst/output/"$file.pgp"; 
rename allfile_123 new_name /usr/tst/output/*.pgp ; done

I know the above doesn't work because $file = /opt/dir/ABC/allfile_123*. Is it possible to make this work, or is it a different command instead of 'for loop'?

This is for the Autosys application in which the jil contains a command to pass to the command line of a linux server running bash.

I could only find versions of each part of my question but not altogether and I was hoping to keep it on the command line of this jil. Unless a script is absolutely necessary.

Upvotes: 4

Views: 1951

Answers (1)

janos
janos

Reputation: 124646

No need for the loop, you can do this with just rename and mv:

rename -v 's/$/.pgp/' /opt/dir/ABC/allfile_123*
rename -v s/allfile_123/new_name/ /opt/dir/ABC/allfile_123*
mv /opt/dir/ABC/new_name* /usr/tst/output/

But I'm not sure the rename you are using is the same as mine. However, since the replacement you want to perform is fairly simple, it's easy to do in pure Bash:

for file in /opt/dir/ABC/allfile_123*; do
    newname=new_name${file##*allfile_123}.gpg
    mv "$file" /usr/tst/output/"$newname"
done

If you want to write it on a single line:

for file in /opt/dir/ABC/allfile_123*; do newname=new_name${file##*allfile_123}.gpg; mv "$file" /usr/tst/output/"$newname"; done

Upvotes: 4

Related Questions