Home > Net >  Script to remove spaces in all files and folders?
Script to remove spaces in all files and folders?

Time:12-13

I wrote a script which removes spaces in a single folder/file name. I want to make it work so that it removes all spaces in folder/files name in the directory the script exists.

MY Script:

#!/bin/bash

var=$(ls | grep " ")

test=$(echo $var | sed 's/ //')

mv "$var" $test

How it worked enter image description here

enter image description here

Thank you for helping!

CodePudding user response:

Try this

ls | grep " " | while read file_name
do 
    mv "$file_name" "$(echo $file_name | sed -E 's/  //g')"
done

sed -E is so that you can use some simple regex, and / / so it can work in case of multiple consecutive spaces such as . And /g so it replaces every occurrences such as foo baa .txt .

CodePudding user response:

Something like this might work:

for f in * ; do
    if [[ "$f" =~ \  ]] ; then
        mv "$f" "${f// /_}"
    fi
done

Explanattion:

for f in * ; do

loops over all file names in the directory. It doesn't have the quirks of ls that make parsing the output of ls a bad idea.

if [[ "$f" =~ \  ]] ; then

This is the bash way of pattern matching. The \ is the pattern. You need to escape the space with a backslash, otherwise the shell will not recognize it as a pattern.

        mv "$f" "${f// /_}"

${f// /_} is the bash way of pattern-substitution. The // means replace all occurrences. The syntax is ${variable//pattern/replacement} to replace all patterns in the variable with the replacement.

  • Related