How to remove spaces from file names

keyboard, how to remove spaces file names

On many occasions you will have come across file names and directories that have intervening spaces in their names, especially those that come from Windows. These spaces are often annoying, especially when working from the shell, since you need to identify them so that they are not treated as separate command names or options. Therefore, in this tutorial we are going to see some ways to remove spaces automatically.

In addition, we will also see how these can be used files or directories with names that have spaces without throwing you an error.

How to use files and directories with spaces

To try to escape spaces of the names of the files and directories in the Linux terminal, you can do it in these ways:

  • Including "" (double quotes) in part of the path where there are spaces or in all of it. For example:
cd "nombre con espacio"/

  • Using a \ character before each space. For example:
nano nombre\ con\ espacio.txt

In these ways, you will bypass these annoying spaces. Now, in order not to have to use these options again, which can be more inconvenient, you can follow the following steps…

How to remove spaces from names

Now, you can use various methods to make these namespaces stop being a problem forever. If you have a large number of names with spaces, it is not logical to do them one by one, but you can automate these tasks to remove or replace spaces:

  • Use the rename command for it. For example, the first of these commands removes spaces from all .txt files, while the second removes spaces from all files within the current directory:

rename 's/\s/_/g' ./*.txt
rename 's/\s/_/g' ./*.*

  • Use find to replace all names that have spaces, replacing them with _. For example, do it with all the .txt of the current directory or of the entire FS:
find . -type f -name "* *.txt" -exec bash -c 'mv "$0" "${0// /_}"' {} \;

**find / -type f -name "* *.txt" -exec bash -c 'mv "$0" "${0// /_}"' {} \;

**Watch out for the second command! You can alter names that are used by certain programs and have them stop working.

Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: AB Internet Networks 2008 SL
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.