bash 对于 `ls` 中的名称和带空格的文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8645546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:24:31  来源:igfitidea点击:

for name in `ls` and filenames with spaces

bashspecial-charactersfilenames

提问by Yola

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

回答by fge

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

只是不要使用命令替换:使用for name in *.

回答by ugoren

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.

注意:bash 变量范围很糟糕。如果您在循环内更改变量,则它不会在循环外生效(在我的版本中不会,在您的版本中会)。在这个例子中,这无关紧要。

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.

注意 2:这适用于带有空格的文件名,但对于其他一些奇怪但有效的文件名无效。请参阅下面的查尔斯·达菲 (Charles Duffy) 的评论。

回答by jaypal singh

Looks like two potential issues:

看起来有两个潜在的问题

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

首先,IFS 变量及其赋值中不应有空格。代替

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

IFS = '\n'它应该是 IFS=$'\n'

Secondly, for name in lswill cause issues with filename having spacesand newlines. If you just wish to handle filenamewith spacesthen do something like this

其次,for name in ls会导致文件名具有spaces和 的问题newlines。如果你只是想处理filenamespaces再这样做

for name in *

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 spacesin new lines. May be that's what you want.

这将为您提供filename with spacesnew lines. 可能这就是你想要的。