Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在BASH中使用文件名中有空格的cat文件?_Bash_Filenames_Cat - Fatal编程技术网

如何在BASH中使用文件名中有空格的cat文件?

如何在BASH中使用文件名中有空格的cat文件?,bash,filenames,cat,Bash,Filenames,Cat,我试着用cat文件名file sth.txt。当我写作时 cat "file sth.txt" 它工作得很好 当我将文件sth.txt保存到变量文件中并执行 cat "$file" 系统写入 cat: file: No such file or directory cat: sth.txt: No such file or directory 我想使用变量cat文件,并在其中包含多个文件名。对于没有空格的文件名,它可以工作。有人能给我一些建议吗?试试这个,这就是Mac OS X终端处理此类

我试着用
cat
文件名
file sth.txt
。当我写作时

cat "file sth.txt"
它工作得很好

当我将
文件sth.txt
保存到变量
文件
中并执行

cat "$file"
系统写入

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

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

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

cat /path/to/file\ sth.txt
您可以对脚本执行相同的操作

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

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

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=
gnubash,Version 4.3.33(1)-发行版(i686 pc cygwin)
您必须这样分配变量:

file="file sth.txt"
或:

使用数组:

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

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

如果您发现自己依赖于单词分割(即,您在命令行上展开的变量被包含的空格分割成多个参数),通常最好使用数组。

我将文件名作为脚本的参数。我有一美元的。文件名是“file sth.txt”。您使用的是
cat“$file”
还是
cat$file
?因为引用的版本应该可以正常工作。如果我的变量中有多个文件,则无法正常工作。怎么做?如果变量包含多个文件名,则不能支持名称中带有空格的文件。不要在同一个变量中放置多个文件名。使用一个数组或多个参数。您使用了什么命令将
文件sth.txt
保存到
$file
# Put all your filenames in an array
arr=("file sth.txt")  # Quotes necessary
arr+=("$1")           # Quotes necessary if $1 contains whitespaces
arr+=("foo.txt") 

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