How to rename a file on Linux by removing certain characters from the file name?

How can I rename a file in linux to cut certain characters from a file name?

For instance,

My123File.txt to be renamed My123.txt

+4
source share
3 answers

If you're okay with just wildcards (not full regular expressions), you can try something like

f='My123File.txt' mv $f ${f/File/} 

This type of shell extension is documented here .

If you really need regular expressions, try

 f='My123File.txt' mv $f $(echo $f | sed -e 's/File//') 
+8
source

User will rename, here is the test:

 $ touch My123File.txt $ rename 's/File//' My123File.txt 

See man rename . rename supports regular expressions, so you can, for example, do this: execute safe, for example. / tmp or so:

 cd /tmp rm *.txt touch My123File.txt My456File.txt ls *.txt rename 's/([A-Za-z]+)(\d+)(\w+)/$3-999-$2-$1/' *.txt ls *.txt 

gives the following:

 My123File.txt My456File.txt File-999-123-My.txt File-999-456-My.txt 
+4
source

With mmv, this one command is much simpler. It also supports translations, such as reducing the positional parameter.

 mmv '*File.txt' '#1.txt' 
0
source

Source: https://habr.com/ru/post/1397941/


All Articles