+5 votes
in Operating Systems by (40.5k points)

I want to add some characters to the filename in the middle of it. There are many files in the folder and I want to do this to all files.

What bash command should I use to do this? 

E.g.

hello-file-1.txt  -> hello-world-file-1.txt

1 Answer

+3 votes
by (346k points)
selected by
 
Best answer

If all of your files have similar names and you want to add some characters to the middle of those filenames, you can use the "mv" command with the "for" loop.

You need to find the position in the filename to add those new characters and specify it as a parameter in the command.

E.g., I have hello-file-1.txt, hello-file-2.txt, ....., hello-file-n.txt in a folder, and I want to change them to hello-world-file-1.txt, hello-world-file-2.txt, ...., hello-world-file-n.txt. Here, I am adding "world-" at the 7th position. So I will run the following bash command on the terminal.

for file in * ;  do mv "$file" "${file:0:6}world-${file:6:16}" ; done

The command does not change anything in positions 0-6, adds "world-" at position 7, and does not change anything in positions 6-16. 16 is the length of the filename.

"cd" to the folder where you have kept the files; then run this command.


...