I wrote code to change the name of bulk of file it should replace spaces with underscores and lowercase all the file name ..

this is the code

for file in *;
do mv "$file" `echo $file | sed -e 's/  */_/g' -e 's/_-_/-/g'`;
do mv -f "$file" `echo "$file" | tr A-Z a-z`;

I know the variable $file will change after the 2nd line so it will give error in the 3rd line

I can divide it into 2 loops and then it will work but I need advise how to overcome this in one for loop only

  • what do you just want to remove all blank spaces and make all capital letters lowercase? – mchid Aug 23 '15 at 7:59

To rename files, it is probably simpler to use perl's rename utility (sometimes called prename). I will assume, though, that you are doing this as an exercise in learning shell scripting.

To fix the immediate problem, all you need is a second shell variable, here called new:

for file in *
    new=$(echo "$file" | sed -e 's/  */_/g' -e 's/_-_/-/g')
    mv -f "$file" "$(echo "$new" | tr A-Z a-z)"

Another approach is to extend the pipeline:

for file in *
    mv -f "$file" "$(echo "$file" | sed -e 's/  */_/g' -e 's/_-_/-/g' | tr A-Z a-z)"

If you have GNU sed, then the pipeline can be simplified further:

for file in *
    mv -f "$file" "$(echo "$file" | sed -e 's/  */_/g' -e 's/_-_/-/g' -e 's/.*/\L&/')"


  1. Since you used the -f option to mv, it is possible that this script will cause files in your directory to be overwritten and their contents lost.

  2. Consider using $(...) in place of backquotes for command substitution. The dollar-parens form nests well, it is visually clear, and it avoids that confusion that happens because many fonts don't show a clear difference between back ticks and regular ticks.

  3. Many languages require a semicolon at the end of each command. shell is not one of those languages: the newline character ends a command just the way a semicolon does.

  • OK thanks , i will go with the second advise to extend the pips – Fat Mind Aug 23 '15 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.