mv files with multiple `.` in the file name

by Jason   Last Updated September 21, 2018 14:01 PM

I have some files I receive with names like (to many to do this manually everyday):

AA.B.txt
WW.C.txt

and I want to rename them to AA_B.txt and WW_C.txt so that existing SQL code still functions as expected. Right now these files are ignored due to the filename.letter.txt format.

ls works and shows me these files:

$ ls -a *.*.txt
AA.B.txt*
ABR.A.txt*
ABR.B.txt*
ABR.C.txt*
ACT.A.txt*

However a similar mv command fails:

$ mv *.*.txt *_*.txt
usage: mv [-f | -i | -n] [-v] source target
       mv [-f | -i | -n] [-v] source ... directory

How do I match the pattern I have with what I want?



Answers 2


mv is not the right tool.

You should use the rename command:

rename 's/\./_/' *.*.txt

The string 's/\./_/' means "substitute the first occurrence of a . with a _ in the folling file list".

Mr Shunz
Mr Shunz
September 21, 2018 13:09 PM

The mv command can only have one target, either renaming one file (e.g. mv AA.B.txt AA_B.txt) or moving a set of files and directories into a directory (e.g. mv ..txt newdir). If you want to rename a file, you need to do it one at a time. So, some kind of loop.

Try something like the following:

for f in *.*.txt; do
    mv ${f} $(echo ${f} | sed -e 's#\.#_#')
done

The sed command replaces just the first dot found with an underscore. Any remaining dots are untouched.

Hope this helps.

Lewis M
Lewis M
September 21, 2018 13:09 PM

Related Questions


Run batch over results of ls command

Updated November 05, 2016 09:00 AM