简体   繁体   English

Shell脚本中文件名中的空格

[英]Whitespace in filenames in shell script

I have a shell script that processes some files. 我有一个处理某些文件的Shell脚本。 The problem is that there might be white spaces in file names, I did: 问题是文件名中可能会有空格,我这样做了:

#!/bin/sh
FILE=`echo $FILE | sed -e 's/[[:space:]]/\\ /g'`
cat $FILE

So the variable FILE is a file name which is passed in from some other program. 因此,变量FILE是从其他程序传入的文件名。 It may contain white spaces. 它可能包含空格。 I used sed to escape white space with \\ in order to make the command line utilities be able to process it. 我使用sed使用\\来转义空格,以使命令行实用程序能够对其进行处理。

The problem is that it doesn't work. 问题是它不起作用。 echo $FILE | sed -e 's/[[:space:]]/\\\\ /g' echo $FILE | sed -e 's/[[:space:]]/\\\\ /g' itself works as expected, but when assigned to FILE , the escape char \\ disappeared again. echo $FILE | sed -e 's/[[:space:]]/\\\\ /g'本身可以正常工作,但是当分配给FILE ,转义字符\\再次消失。 As a result, cat will interpret it as more than 1 arguments. 结果, cat会将其解释为1个以上的参数。 I wonder why it behaves like this? 我想知道为什么会这样吗? Is there anyway to avoid it? 反正有避免的方法吗? And what if there're multiple white spaces, say some terrible file.txt , which should be replaced by some\\ \\ \\ terrible\\ \\ file.txt . 还有,如果有多个空格,说some terrible file.txt ,应将其替换为some\\ \\ \\ terrible\\ \\ file.txt Thanks. 谢谢。

Don't try to put escape characters inside your data -- they're only honored as syntax (that is, backslashes have meaning when found in your source code , not your data). 请勿尝试在数据中放入转义字符-它们仅作为语法而受到尊重(也就是说,反斜杠在源代码中才有意义,而不是在数据中)。

That is to say, the following works perfectly, exactly as given: 也就是说,以下内容完全可以正常工作:

file='some   terrible  file.txt'
cat "$file"

...likewise if the name comes from a glob result or similar: ...同样,如果名称来自全局结果或类似结果:

# this operates in a temporary directory to not change the filesystem you're running it in
tempdir=$(mktemp -d "${TMPDIR:-/tmp}/testdir.XXXXXX") && (
  cd "$tempdir" || exit
  echo 'example' >'some  terrible  file.txt'
  for file in *.txt; do
    printf 'Found file %q with the following contents:\n' "$file"
    cat "$file"
  done
  rm -rf "$tempdir"
)

Don't make it more complicated than it is. 不要让它变得比现在更复杂。

cat "$FILE"

That's all you need. 这就是您所需要的。 Note the quotes around the variable. 注意变量周围的引号。 They prevent the variable from being expanded and split at whitespace. 它们防止变量在空白处扩展和分割。 You should always write your shell programs like that. 您应该始终像这样编写Shell程序。 Always put quotes around all your variables, unless you really want the shell to expand them. 除非您确实希望shell扩展它们,否则请始终在所有变量周围加上引号。

for i in $pattern; do

That would be ok. 没关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM