Loop over files with spaces in their names, create new folder from first character in each file and move...

I'm attempting to understand my 401k match and how much I need to contribute to maximize the match

What happens when the drag force exceeds the weight of an object falling into earth?

Why doesn't Dany protect her dragons better?

Names of the Six Tastes

logo selection for poster presentation

Why is there a cap on 401k contributions?

Light Switch Neutrals: Bundle all together?

"I can't place her": How do Russian speakers express this idea colloquially?

What's an appropriate age to involve kids in life changing decisions?

How long can fsck take on a 30 TB volume?

How is it believable that Euron could so easily pull off this ambush?

99 coins into the sacks

Why doesn't increasing the temperature of something like wood or paper set them on fire?

Are there vaccine ingredients which may not be disclosed ("hidden", "trade secret", or similar)?

Can the president of the United States be guilty of insider trading?

How can I test a shell script in a "safe environment" to avoid harm to my computer?

What should I use to get rid of some kind of weed in my onions

Whose birthyears are canonically established in the MCU?

How to adjust Venn Diagram for A^c and A - B

How would an instant or sorcery with an effect that targets work with Feather?

The unknown and unexplained in science fiction

mini sub panel?

Why is it wrong to *implement* myself a known, published, widely believed to be secure crypto algorithm?

Identity of a supposed anonymous referee revealed through "Description" of the report



Loop over files with spaces in their names, create new folder from first character in each file and move files to folders


Why *not* parse `ls` (and what do to instead)?Create a new link to access all files and foldersMove files to multiple foldersgrep two searched wordscannot move Directory not emptyCannot mv to a subdirectory of itself7zip and Move Files with Spaces in Bash ScriptOptimize find -exec {} with multiple conditions : specific files in a dir and specific subdirectories in this dirCreating text file with content within a mkdir listRead from a file and return new line with loopCreate files inside folders with spaces in name with bash script






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







1















I'm trying to execute this bash script that loops over files (that have spaces in the name) in the current directory and creates a new folder with the first character of the file (if not already created) and moves that file to the folder. This is my code:



for i in `/bin/ls | xargs`
do
dir=`echo "$i" | cut -c 1 -`
mkdir -m777 -p "$dir"
mv "$i" "$dir"
done


The problem with this seems to be that it treats the each word in the file as a separate file, so although it creates the folder correctly , it can't move the file to that folder because the name of the file that it looks for is only the first word of the actual file. I looked at other answers to similar questions but this is the closest I've been able to get.



EDIT:
I replaced " for i in /bin/ls | xargs " with " for i in * " as @steeldriver suggested, and although it fixed my original problem, I'm getting errors like these:



mv: cannot move '`' to a subdirectory of itself, '`/`'
mv: invalid option -- ' '
mv: missing destination file operand after '-'
mv: invalid option -- '.'
mv: invalid option -- ')'
mv: invalid option -- '+'
mv: cannot move ''$'340' to a subdirectory of itself, ''$'340''/'$'340'
mv: cannot move ''$'303' to a subdirectory of itself, ''$'303''/'$'303'
mv: cannot move ''$'305' to a subdirectory of itself, ''$'305''/'$'305'
mv: invalid option -- '1'


I think some of these files may start with non-ascii characters (I can't view the contents because there are too many files). Is there a work around to handle these cases?










share|improve this question









New contributor



Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    for i in *; do ... - see Bash Pitfall #1

    – steeldriver
    4 hours ago











  • Welcome to Unix & Linux! It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here.

    – DopeGhoti
    4 hours ago











  • Also, this will fail if you already (for example) have a file called t.

    – DopeGhoti
    4 hours ago


















1















I'm trying to execute this bash script that loops over files (that have spaces in the name) in the current directory and creates a new folder with the first character of the file (if not already created) and moves that file to the folder. This is my code:



for i in `/bin/ls | xargs`
do
dir=`echo "$i" | cut -c 1 -`
mkdir -m777 -p "$dir"
mv "$i" "$dir"
done


The problem with this seems to be that it treats the each word in the file as a separate file, so although it creates the folder correctly , it can't move the file to that folder because the name of the file that it looks for is only the first word of the actual file. I looked at other answers to similar questions but this is the closest I've been able to get.



EDIT:
I replaced " for i in /bin/ls | xargs " with " for i in * " as @steeldriver suggested, and although it fixed my original problem, I'm getting errors like these:



mv: cannot move '`' to a subdirectory of itself, '`/`'
mv: invalid option -- ' '
mv: missing destination file operand after '-'
mv: invalid option -- '.'
mv: invalid option -- ')'
mv: invalid option -- '+'
mv: cannot move ''$'340' to a subdirectory of itself, ''$'340''/'$'340'
mv: cannot move ''$'303' to a subdirectory of itself, ''$'303''/'$'303'
mv: cannot move ''$'305' to a subdirectory of itself, ''$'305''/'$'305'
mv: invalid option -- '1'


I think some of these files may start with non-ascii characters (I can't view the contents because there are too many files). Is there a work around to handle these cases?










share|improve this question









New contributor



Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    for i in *; do ... - see Bash Pitfall #1

    – steeldriver
    4 hours ago











  • Welcome to Unix & Linux! It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here.

    – DopeGhoti
    4 hours ago











  • Also, this will fail if you already (for example) have a file called t.

    – DopeGhoti
    4 hours ago














1












1








1








I'm trying to execute this bash script that loops over files (that have spaces in the name) in the current directory and creates a new folder with the first character of the file (if not already created) and moves that file to the folder. This is my code:



for i in `/bin/ls | xargs`
do
dir=`echo "$i" | cut -c 1 -`
mkdir -m777 -p "$dir"
mv "$i" "$dir"
done


The problem with this seems to be that it treats the each word in the file as a separate file, so although it creates the folder correctly , it can't move the file to that folder because the name of the file that it looks for is only the first word of the actual file. I looked at other answers to similar questions but this is the closest I've been able to get.



EDIT:
I replaced " for i in /bin/ls | xargs " with " for i in * " as @steeldriver suggested, and although it fixed my original problem, I'm getting errors like these:



mv: cannot move '`' to a subdirectory of itself, '`/`'
mv: invalid option -- ' '
mv: missing destination file operand after '-'
mv: invalid option -- '.'
mv: invalid option -- ')'
mv: invalid option -- '+'
mv: cannot move ''$'340' to a subdirectory of itself, ''$'340''/'$'340'
mv: cannot move ''$'303' to a subdirectory of itself, ''$'303''/'$'303'
mv: cannot move ''$'305' to a subdirectory of itself, ''$'305''/'$'305'
mv: invalid option -- '1'


I think some of these files may start with non-ascii characters (I can't view the contents because there are too many files). Is there a work around to handle these cases?










share|improve this question









New contributor



Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I'm trying to execute this bash script that loops over files (that have spaces in the name) in the current directory and creates a new folder with the first character of the file (if not already created) and moves that file to the folder. This is my code:



for i in `/bin/ls | xargs`
do
dir=`echo "$i" | cut -c 1 -`
mkdir -m777 -p "$dir"
mv "$i" "$dir"
done


The problem with this seems to be that it treats the each word in the file as a separate file, so although it creates the folder correctly , it can't move the file to that folder because the name of the file that it looks for is only the first word of the actual file. I looked at other answers to similar questions but this is the closest I've been able to get.



EDIT:
I replaced " for i in /bin/ls | xargs " with " for i in * " as @steeldriver suggested, and although it fixed my original problem, I'm getting errors like these:



mv: cannot move '`' to a subdirectory of itself, '`/`'
mv: invalid option -- ' '
mv: missing destination file operand after '-'
mv: invalid option -- '.'
mv: invalid option -- ')'
mv: invalid option -- '+'
mv: cannot move ''$'340' to a subdirectory of itself, ''$'340''/'$'340'
mv: cannot move ''$'303' to a subdirectory of itself, ''$'303''/'$'303'
mv: cannot move ''$'305' to a subdirectory of itself, ''$'305''/'$'305'
mv: invalid option -- '1'


I think some of these files may start with non-ascii characters (I can't view the contents because there are too many files). Is there a work around to handle these cases?







shell-script






share|improve this question









New contributor



Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 3 hours ago







Logan













New contributor



Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 4 hours ago









LoganLogan

113




113




New contributor



Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




Logan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










  • 1





    for i in *; do ... - see Bash Pitfall #1

    – steeldriver
    4 hours ago











  • Welcome to Unix & Linux! It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here.

    – DopeGhoti
    4 hours ago











  • Also, this will fail if you already (for example) have a file called t.

    – DopeGhoti
    4 hours ago














  • 1





    for i in *; do ... - see Bash Pitfall #1

    – steeldriver
    4 hours ago











  • Welcome to Unix & Linux! It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here.

    – DopeGhoti
    4 hours ago











  • Also, this will fail if you already (for example) have a file called t.

    – DopeGhoti
    4 hours ago








1




1





for i in *; do ... - see Bash Pitfall #1

– steeldriver
4 hours ago





for i in *; do ... - see Bash Pitfall #1

– steeldriver
4 hours ago













Welcome to Unix & Linux! It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here.

– DopeGhoti
4 hours ago





Welcome to Unix & Linux! It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here.

– DopeGhoti
4 hours ago













Also, this will fail if you already (for example) have a file called t.

– DopeGhoti
4 hours ago





Also, this will fail if you already (for example) have a file called t.

– DopeGhoti
4 hours ago










2 Answers
2






active

oldest

votes


















1














To loop over files with spaces in their names, the shell is plenty, no need to call ls:



for    i in *                   # * replaces the complex (and unquoted) `/bin/ls | xargs`
do
dir=${i%"${i#?}"} # replaces the slow subshell `echo "$i" | cut -c 1 -`

echo "$i" # just to show that an * is enough (and accepts spaces).
done


And to process each file listed (which include directories) you should check that the filename is a file (not a directory) and also check if the directory doesn't exist before creating it.



for i in *
do
if [ -f "$i" ]; then
dir=${i%"${i#?}"}
if [ ! -d "$dir" ]; then
mkdir -m777 -p "$dir"
fi
mv "$i" "$dir"
if [ "$?" -ne 0 ]; then
echo "An error occurred moving file "$i" to dir "$dir""
fi
fi
done





share|improve this answer

































    0














    With GNU Parallel it looks like this:



    parallel 'mkdir -p {=s/(.).*/$1/=}; mv {} {=s/(.).*/$1/=}' ::: *


    (Edit: Just noted you are asking for files - not dirs. / is removed).






    share|improve this answer


























    • When I try this, I get the error: mv: cannot move '/' to a subdirectory of itself, '*/'

      – Logan
      3 hours ago












    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "106"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    Logan is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f517665%2floop-over-files-with-spaces-in-their-names-create-new-folder-from-first-charact%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    To loop over files with spaces in their names, the shell is plenty, no need to call ls:



    for    i in *                   # * replaces the complex (and unquoted) `/bin/ls | xargs`
    do
    dir=${i%"${i#?}"} # replaces the slow subshell `echo "$i" | cut -c 1 -`

    echo "$i" # just to show that an * is enough (and accepts spaces).
    done


    And to process each file listed (which include directories) you should check that the filename is a file (not a directory) and also check if the directory doesn't exist before creating it.



    for i in *
    do
    if [ -f "$i" ]; then
    dir=${i%"${i#?}"}
    if [ ! -d "$dir" ]; then
    mkdir -m777 -p "$dir"
    fi
    mv "$i" "$dir"
    if [ "$?" -ne 0 ]; then
    echo "An error occurred moving file "$i" to dir "$dir""
    fi
    fi
    done





    share|improve this answer






























      1














      To loop over files with spaces in their names, the shell is plenty, no need to call ls:



      for    i in *                   # * replaces the complex (and unquoted) `/bin/ls | xargs`
      do
      dir=${i%"${i#?}"} # replaces the slow subshell `echo "$i" | cut -c 1 -`

      echo "$i" # just to show that an * is enough (and accepts spaces).
      done


      And to process each file listed (which include directories) you should check that the filename is a file (not a directory) and also check if the directory doesn't exist before creating it.



      for i in *
      do
      if [ -f "$i" ]; then
      dir=${i%"${i#?}"}
      if [ ! -d "$dir" ]; then
      mkdir -m777 -p "$dir"
      fi
      mv "$i" "$dir"
      if [ "$?" -ne 0 ]; then
      echo "An error occurred moving file "$i" to dir "$dir""
      fi
      fi
      done





      share|improve this answer




























        1












        1








        1







        To loop over files with spaces in their names, the shell is plenty, no need to call ls:



        for    i in *                   # * replaces the complex (and unquoted) `/bin/ls | xargs`
        do
        dir=${i%"${i#?}"} # replaces the slow subshell `echo "$i" | cut -c 1 -`

        echo "$i" # just to show that an * is enough (and accepts spaces).
        done


        And to process each file listed (which include directories) you should check that the filename is a file (not a directory) and also check if the directory doesn't exist before creating it.



        for i in *
        do
        if [ -f "$i" ]; then
        dir=${i%"${i#?}"}
        if [ ! -d "$dir" ]; then
        mkdir -m777 -p "$dir"
        fi
        mv "$i" "$dir"
        if [ "$?" -ne 0 ]; then
        echo "An error occurred moving file "$i" to dir "$dir""
        fi
        fi
        done





        share|improve this answer















        To loop over files with spaces in their names, the shell is plenty, no need to call ls:



        for    i in *                   # * replaces the complex (and unquoted) `/bin/ls | xargs`
        do
        dir=${i%"${i#?}"} # replaces the slow subshell `echo "$i" | cut -c 1 -`

        echo "$i" # just to show that an * is enough (and accepts spaces).
        done


        And to process each file listed (which include directories) you should check that the filename is a file (not a directory) and also check if the directory doesn't exist before creating it.



        for i in *
        do
        if [ -f "$i" ]; then
        dir=${i%"${i#?}"}
        if [ ! -d "$dir" ]; then
        mkdir -m777 -p "$dir"
        fi
        mv "$i" "$dir"
        if [ "$?" -ne 0 ]; then
        echo "An error occurred moving file "$i" to dir "$dir""
        fi
        fi
        done






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 3 hours ago

























        answered 3 hours ago









        IsaacIsaac

        12.4k11955




        12.4k11955

























            0














            With GNU Parallel it looks like this:



            parallel 'mkdir -p {=s/(.).*/$1/=}; mv {} {=s/(.).*/$1/=}' ::: *


            (Edit: Just noted you are asking for files - not dirs. / is removed).






            share|improve this answer


























            • When I try this, I get the error: mv: cannot move '/' to a subdirectory of itself, '*/'

              – Logan
              3 hours ago
















            0














            With GNU Parallel it looks like this:



            parallel 'mkdir -p {=s/(.).*/$1/=}; mv {} {=s/(.).*/$1/=}' ::: *


            (Edit: Just noted you are asking for files - not dirs. / is removed).






            share|improve this answer


























            • When I try this, I get the error: mv: cannot move '/' to a subdirectory of itself, '*/'

              – Logan
              3 hours ago














            0












            0








            0







            With GNU Parallel it looks like this:



            parallel 'mkdir -p {=s/(.).*/$1/=}; mv {} {=s/(.).*/$1/=}' ::: *


            (Edit: Just noted you are asking for files - not dirs. / is removed).






            share|improve this answer















            With GNU Parallel it looks like this:



            parallel 'mkdir -p {=s/(.).*/$1/=}; mv {} {=s/(.).*/$1/=}' ::: *


            (Edit: Just noted you are asking for files - not dirs. / is removed).







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 3 hours ago

























            answered 4 hours ago









            Ole TangeOle Tange

            13.2k1658107




            13.2k1658107













            • When I try this, I get the error: mv: cannot move '/' to a subdirectory of itself, '*/'

              – Logan
              3 hours ago



















            • When I try this, I get the error: mv: cannot move '/' to a subdirectory of itself, '*/'

              – Logan
              3 hours ago

















            When I try this, I get the error: mv: cannot move '/' to a subdirectory of itself, '*/'

            – Logan
            3 hours ago





            When I try this, I get the error: mv: cannot move '/' to a subdirectory of itself, '*/'

            – Logan
            3 hours ago










            Logan is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            Logan is a new contributor. Be nice, and check out our Code of Conduct.













            Logan is a new contributor. Be nice, and check out our Code of Conduct.












            Logan is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f517665%2floop-over-files-with-spaces-in-their-names-create-new-folder-from-first-charact%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...