Skip to main content
edited tags
Link
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 264
Source Link

Loop through directory with space in the name

I am trying to write a script that will loop through directories, and rename the file in the sub directory to match that of the directory name. I am running into an issue where if a directory has spaces in the name, then that name is split up and I can't do anything with it like I need to.

For example, the folder structure is:

TopLevel
->this is a test
-->test.txt

My script so far is:

#!/bin/sh
topLevel="/dir1/dir2/TopLevel"
for dir in $(ls $topLevel)
do
    echo $dir # for testing purposes to make sure i'm getting the right thing
    # Get name of directory - i know how to do this
    # Rename file to match the name of the directory, with the existing extension - i know how to do this
done

My expected output would be

/dir1/dir2/TopLevel/this is a test

However, the actual output is

this
is
a
test

Can someone point me in the right direction? It's been awhile since I've done shell scripting. I'm trying to take this script one piece at a time and I seem to be stuck on getting this iteration down.