list directory with spaces shell script

Posted on 2011-10-05
Last Modified: 2012-05-12
or file in `ls`; do echo "cp -R $dir  ./dir2/";  done
This works great except directories with spaces do not work as expected.  For example directory name  sales and returns

cp -R /dir1/sales  /dir2/
cp -R/dir1/and  /dir2/
cp -R /dir1/returns  /dir2/

I should get
cp -R /dir1/sales and returns  /dir2/

How do I stop directory names with spaces from being split?

I'll close the question after this (-: thanks all.
Question by:dplinnane
    LVL 4

    Assisted Solution

    this should be able to help
    ls|while read dir; do echo "cp -R \"$dir\"  ./dir2/";  done
    LVL 48

    Accepted Solution

    Simply do

    cp -R * ../dir2

    Open in new window

    LVL 4

    Assisted Solution

    I always use this:

    or file in `ls | sed -e 's/.*/"&"/g'`; do echo "cp -R $dir  ./dir2/";  done

    But basically this will wrap each line output from ls in double quotes...

    .* - match whole line
    "&" - & is replaced by the search result and the double quotes are literals inside of the single quoted arg...


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
    Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
    Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    23 Experts available now in Live!

    Get 1:1 Help Now