Craig155
Craig155

Reputation: 83

Renaming files with various extensions

I have a folder of files which contains a variety of random file extensions as well as no extensions at all. I wish to strip the extensions from the file name. I feel I may be going a long winded way but I wanted to avoid using two lists and the move command as it cannot be conducted on-the-fly.

The code I am using will create a variable to keep the extension and I am trying to invoke the rename command with the sed syntax to strip the variable from the file.

for i in `ls`; do 
        blah=$(echo $i |awk -F . '{if (NF>1) {print $NF}}')
        echo \.$blah
        rename 's/\.$blah//' $i  

done 

The error I am getting is: Global symbol "$blah" requires explicit package name at (eval 1) line 1

At this point I am going to build a csv with a before and after column and use it to strip the file name but for future reference I would like to know how to accomplish this.

I see allot of posts about using rename for a single or a few extensions:

rename 's/.mp3//' *.mp3

but due to the number of different extensions...

Upvotes: 3

Views: 517

Answers (3)

abasu
abasu

Reputation: 2524

if you want, you can use the bash parameter expansion to strip the extension. Also you dont need and ls to get all the files

for i in *; do echo "$i to ${i%.*}" mv "$i" "${i%.*}"; done

Now for a.b.c -> a use "%%" , and for a.b, use "%" as above

Update : ( for file with space in name)

[[bash_prompt$]]$ ls -l
total 0
[[bash_prompt$]]$ touch "file space.sh" "another space .sh"
[[bash_prompt$]]$ ls
another space .sh  file space.sh
[[bash_prompt$]]$ for i in *; do mv "$i" "${i%%.*}"; done
[[bash_prompt$]]$ ls
another space   file space

Upvotes: 2

choroba
choroba

Reputation: 241868

rename in your system is implemented in Perl, that's where the error comes from. You used single quotes, which means the variable was not expanded, and Perl did not find the definition of a variable $blah.

Also, for i in `ls` might be wrong if your file names contain spaces. It is better to use a wildcard, as in

for i in *.*

What do you want to do for files whose names without extensions are identical, like good.mp3 and good.jpg? Do you want to overwrite one of them?

To use rename on all files with extensions, you can try

rename 's/\..*//' *.*

It would still overwrite some files as noted before. Also, files with names like a.b.c.d would be renamed to a only.

Upvotes: 4

Birei
Birei

Reputation: 36262

Following bash command should do the job:

for f in *.*; do mv "$f" "${f%.*}"; done

Upvotes: 5

Related Questions