繁体   English   中英

Shell脚本中文件名中的空格

[英]Whitespace in filenames in shell script

我有一个处理某些文件的Shell脚本。 问题是文件名中可能会有空格,我这样做了:

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

因此,变量FILE是从其他程序传入的文件名。 它可能包含空格。 我使用sed使用\\来转义空格,以使命令行实用程序能够对其进行处理。

问题是它不起作用。 echo $FILE | sed -e 's/[[:space:]]/\\\\ /g' echo $FILE | sed -e 's/[[:space:]]/\\\\ /g'本身可以正常工作,但是当分配给FILE ,转义字符\\再次消失。 结果, cat会将其解释为1个以上的参数。 我想知道为什么会这样吗? 反正有避免的方法吗? 还有,如果有多个空格,说some terrible file.txt ,应将其替换为some\\ \\ \\ terrible\\ \\ file.txt 谢谢。

请勿尝试在数据中放入转义字符-它们仅作为语法而受到尊重(也就是说,反斜杠在源代码中才有意义,而不是在数据中)。

也就是说,以下内容完全可以正常工作:

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

...同样,如果名称来自全局结果或类似结果:

# 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"
)

不要让它变得比现在更复杂。

cat "$FILE"

这就是您所需要的。 注意变量周围的引号。 它们防止变量在空白处扩展和分割。 您应该始终像这样编写Shell程序。 除非您确实希望shell扩展它们,否则请始终在所有变量周围加上引号。

for i in $pattern; do

没关系

暂无
暂无

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

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