Monday, October 25, 2021

[SOLVED] Replace spaces in all files in a directory with underscores

Issue

I have found some similar questions here but not this specific one and I do not want to break all my files. I have a list of files and I simply need to replace all spaces with underscores. I know this is a sed command but I am not sure how to generically apply this to every file.

I do not want to rename the files, just modify them in place.

Edit: To clarify, just in case it's not clear, I only want to replace whitespace within the files, file names should not be changed.


Solution

find . -type f -exec sed -i -e 's/ /_/g' {} \;

find grabs all items in the directory (and subdirectories) that are files, and passes those filenames as arguments to the sed command using the {} \; notation. The sed command it appears you already understand.

if you only want to search the current directory, and ignore subdirectories, you can use

find . -maxdepth 1 -type f -exec sed -i -e 's/ /_/g' {} \;


Answered By - jeremysprofile