0

I have a directory with the files names as "a b c.jpg", "d e f 0.jpg", "g h i.jpg"

I need a script to have all the files ending with "0.jpg" to become "_0.jpg"

So, in the above example the second file should become "d e f_0.jpg"

3 Answers 3

5

I think your question should read that you want files ending with " 0.jpg" to become "_0.jpg" (note the space in the first quotes). That makes sense with your example.

for i in *\ 0.jpg ; do mv -- "$i" "${i/ 0.jpg/_0.jpg}" done 

That is, for every file matching the pattern "* 0.jpg", rename it replacing " 0.jpg" with "_0.jpg"

Edit: For added safety, consider using -n (no-clobber) or -i (interactive) as an option to mv(1).

Sign up to request clarification or add additional context in comments.

3 Comments

Good solution, +1. You might want to write mv -- "$i" to guard agains filenames starting with a dash.
Good point. Since we're using bash, we probably have GNU mv. Added.
hi, please explain which technique you are using here? I don't get it. "${i/ 0.jpg/_0.jpg}"
1

The rename tool might be what you need.

1 Comment

That's part of MySQL so it may not be installed. Also, it works on the contents not the names of file.
-3
ls -1 | grep .jpg | awk -F "." '{print $1 "_0." $2}' 

2 Comments

This deserves at least three downvotes. Never use ls in scripts, never use grep to match filenames, don't use external tools if there is a simpler builtin solution.
It's worse than that: this doesn't actually rename anything, it just prints a list of new names. And it doesn't replace " 0" with "_0", it adds "_0". And it does this for all .jpg files, not just those ending in " 0.jpg". And if any of the filenames have additional period characters in them, it gets even sillier.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.