How to remove numbers from extensions from files

262 views Asked by At

I have many files in a directory having extension like .text(2) and .text(1). I want to remove the numbers from extension and output should be like .text and .text . can anyone please help me with the shell script for that? I am using centOs.

3

There are 3 answers

2
Tom Fenech On BEST ANSWER

A pretty portable way of doing it would be this:

for i in *.text*; do mv "$i" "$(echo "$i" | sed 's/([0-9]\{1,\})$//')"; done

Loop through all files which end in .text followed by anything. Use sed to remove any parentheses containing one or more digits from the end of each filename.

If all of the numbers within the parentheses are single digits and you're using bash, you could also use built-in parameter expansion:

for i in *.text*; do mv "$i" "${i%([0-9])}"; done

The expansion removes any parentheses containing a single digit from the end of each filename.

0
josifoski On

Most simple way if files are in same folder

rename 's/text\([0-9]+\)/text/' *.text*  

link

0
Julio On

Another way without loops, but also with sed (and all the regexp's inside) is piping to sh:

ls *text* | sed 's/\(.*\)\..*/mv  \1* \1.text/' | sh

Example:

[...]$ ls
  xxxx.text(1) yyyy.text(2)
[...]$ ls *text* | sed 's/\(.*\)\..*/mv \1* \1.text/' | sh
[...]$ ls
  xxxx.text yyyy.text

Explanation:

Everything between \( and \) is stored and can be pasted again by \1 (or \2, \3, ... a consecutive number for each pair of parentheses used). Therefore, the code above stores all the characters before the first dot \. and after that, compounds a sequence like this:

mv  xxxx* xxxx.text
mv  yyyy* yyyy.text

That is piped to sh