bash 如何在BASH中的文件名中有空格的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29437042/
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-18 12:43:53  来源:igfitidea点击:

How to cat file with space in filename in BASH?

bashfilenamescat

提问by Jan Bednar

I tried to catfile with name file sth.txt. When I write

我试图cat用 name 归档file sth.txt。当我写

cat "file sth.txt"

It works great.

它工作得很好。

When I save the file sth.txtinto variable fileand I execute

当我保存file sth.txtinto 变量file并执行时

cat "$file"

System writes

系统写入

cat: file: No such file or directory
cat: sth.txt: No such file or directory

I want to catfile with variable and have in it more than one filename. For filenames without space it works. Can anybody give me some advice?

我想cat用变量归档并在其中包含多个文件名。对于没有空格的文件名,它可以工作。有人可以给我一些建议吗?

回答by Michael Jaros

You have to assign the variable like this:

您必须像这样分配变量:

file="file sth.txt"

or:

或者:

file=""

回答by rr-

Are you sure your variable contains correct data? You should escape the path in the variable as well, either with ""or '', or by using \?:

您确定您的变量包含正确的数据吗?您也应该使用""''或使用 来转义变量中的路径\?

rr-@luna:~$ echo test > "file sth.txt"
rr-@luna:~$ var=file\ sth.txt
rr-@luna:~$ cat "$var"
test
rr-@luna:~$ var="file sth.txt"
rr-@luna:~$ cat "$var"
test

Version = GNU bash, version 4.3.33(1)-release (i686-pc-cygwin)

版本 = GNU bash, version 4.3.33(1)-release (i686-pc-cygwin)

回答by weibeld

Use an array:

使用数组:

# Put all your filenames in an array
arr=("file sth.txt")  # Quotes necessary
arr+=("")           # Quotes necessary if  contains whitespaces
arr+=("foo.txt") 

# Expand each element of the array as a separate argument to cat
cat "${arr[@]}"       # Quotes necessary

If you find yourself relying on word splitting (i.e. the fact that variables that you expand on the command line are split into to multiple arguments by the whitespaces they contain), it's often better to use an array.

如果您发现自己依赖于分词(即,您在命令行上展开的变量被它们包含的空格拆分为多个参数这一事实),通常最好使用数组。

回答by ForceBru

Try this, this is the way Mac OS X's Terminal deals with such cases.

试试这个,这就是 Mac OS X 的终端处理这种情况的方式。

cat /path/to/file\ sth.txt

You can do the same with your script

你可以用你的脚本做同样的事情

sh script.sh /path/to/file\ sth.txt