我有一个 bash/shell 函数,它应该查找文件,然后 awk/将它找到的第一个文件复制到另一个目录。不幸的是,如果包含 file
的目录的名称中有空格,那么整个过程都会失败,因为它会出于某种原因截断路径。我该如何解决?
如果 file.txt 在/path/to/search/spaces are bad/它会失败。
dir=/path/to/destination/ | find /path/to/search -name file.txt | head -n 1 | awk -v dir="$dir" '{printf "cp \"%s\" \"%s\"\n", $1, dir}' | sh
cp: /path/to/search/spaces: No such file or directory
*如果 file.txt 在/path/to/search/spacesarebad/它有效,但请注意没有空格。 :-/
最佳答案
Awk 的默认分隔符是空格。只需将其更改为其他内容即可:
awk -F"\t" ...
你的脚本应该是这样的:
dir=/path/to/destination/ | find /path/to/search -name file.txt | head -n 1 | awk -F"\t" -v dir="$dir" '{printf "cp \"%s\" \"%s\"\n", $1, dir}' | sh
正如评论所指出的,您实际上并不需要所有这些步骤,您实际上可以简单地执行(一行):
dir=/path/to/destination/ && path="$(find /path/to/search -name file.txt | head -n 1)" && cp "$path" "$dir"
格式化代码(在本例中可能看起来更好 ^^):
dir=/path/to/destination/
path="$(find /path/to/search -name file.txt | head -n 1)"
cp "$path" "$dir"
""
用于将字符串的全部内容赋值给变量,导致默认为空格的分隔符IFS
不显示考虑过字符串。
关于Bash/Shell - 带空格的路径搞砸了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14130093/