Question

Sorry if this is very simple compared to usual questions but I am just starting out. I have some files all with the same start name but of different file types, e.g:

1234.x
1234.y
1234.z
1234_V2.x
1234_V2.y
1234_V2.z

I want to rename the first part of these whilst keeping any ending and file type, e.g:

4321.x
4321.y
4321.z
4321_V2.x etc

I have tried using

mv 1234* 4321* 

and

rename 1234* 4321*

But no luck! I have also been through all the other SO articles and although I could use a loop, most depend on the file type being the same.

Thanks in advance

Was it helpful?

Solution

You can use bash substitution:

for file in 1234* 
do mv "$file" "4321${file#1234}"
done

OR, replace the do mv with the following

do mv "$file" "${file/1234/4321}"

See more in man bash under EXPANSION section, sub-section Parameter Expansion

OTHER TIPS

Assuming your filenames for 1234 and 4321 i.e constant for all files, you can try this

for fn in `find . -name 1234*` 
do 
    newf=`echo $fn | sed s/1234/4321/`
    mv $fn $newfn
done

You can use a shell script, but it's kind of ugly because it will fork a lot, and thus, if you have a lot of files to rename, it will take time.

for f in 1234*; do echo mv $f $(echo $f | sed -e 's/1234/4321/'); done

Otherwize, rename is a good way to do it:

rename 's/1234/4321/' 1234*

Rename expects a regular expression as first parameter, see online documentation

See if it works:

rename "s/1234/4321/" 1234*

command means substitute(because of s) occurances of "1234" with "4321" in files that has name of pattern 1234*

You can also look at here. It is slightly more complicated than your case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top