Bash/Shell - 带空格的路径搞砸了

标签 bash awk find

我有一个 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/

相关文章:

linux - bash 脚本错误 - 为变量赋值

awk - 使用 awk 按欧氏距离选择数据

c++ - 使用 2 个分隔符 '+' 和 '-"在 C++ 中拆分字符串

string - 有效/简洁地检查可变内容的开始/结束

linux - Bash 列出两个日期之间的日期时间

bash - zsh 循环多个参数

linux - 杀死命令中特定值位于特定范围之间的进程

xml - 如何使用 awk 解析逗号分隔值 (csv)?

linux - 如何删除 3 小时前创建的 linux 目录中的文件

javascript - 使用 JQuery 查找数据属性