for name in `ls` and filenames with spaces

会有一股神秘感。 提交于 2019-11-26 14:06:42

问题


next code doesnt work because of spaces in file names, How to fix?

IFS = '\n'
for name in `ls `
do
    number=`echo "$name" | grep -o "[0-9]\{1,2\}"`
    if [[ ! -z "$number" ]]; then
        mv "$name" "./$number"
    fi
done

回答1:


Just don't use command substitution: use for name in *.




回答2:


Replace

for name in `ls`

with:

ls | while read name

Notice: bash variable scoping is awful. If you change a variable inside the loop, it won't take effect outside the loop (in my version it won't, in your version it will). In this example, it doesn't matter.

Notice 2: This works for file names with spaces, but fails for some other strange but valid file names. See Charles Duffy's comment below.




回答3:


Looks like two potential issues:

First, the IFS variable and it's assignment should not have space in them. Instead of

IFS = '\n' it should be IFS=$'\n'

Secondly, for name in ls will cause issues with filename having spaces and newlines. If you just wish to handle filename with spaces then do something like this

for name in *

I don't understand the significance of the line

number=`echo "$name" | grep -o "[0-9]\{1,2\}"`

This will give you numbers found in filename with spaces in new lines. May be that's what you want.



来源:https://stackoverflow.com/questions/8645546/for-name-in-ls-and-filenames-with-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!