Harshit Singhvi Harshit Singhvi - 9 months ago 86
Bash Question

Rename multiple files changing the extension and part of the string

I have list of

*.new
files in a directory. These file contains
D1
in their names which is to be replaced to
D2
and also have to remove the extension from .new to nothing

hello_world_D1_122.txt.new -------> hello_world_D2_122.txt


What I tried is

ls -slt | grep -iE "*.new$" | awk -F " " '{print $10}' | xargs -I {} mv {} "echo {} | sed -e 's/.D1./.D2./g ; s/.new//g'"


This command is not producing the required output. Output of the above command is

mv: rename hello_world_D1_122.txt.new to echo hello_world_D1_122.txt.new | sed -e 's/D1/D2/g ; s/.new//g': No such file or directory

Answer Source

Using xargs (suppose there are only simple filenames):

[STEP 100] # echo $BASH_VERSION
4.4.12(4)-release
[STEP 101] # ls -1
foo1.txt
foo2.txt
[STEP 102] # ls foo*.txt | xargs -I{} bash -c 'mv $0 ${0/foo/bar}' {}
[STEP 103] # ls -1
bar1.txt
bar2.txt
[STEP 104] #
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download