如何在 bash 脚本中向文件名包含空格的文件添加一些内容?

问题描述 投票:0回答:2

我的代码喜欢

target_file="target/middle dir/filename"
echo -e "Something New\n$(cat $target_file)" > "$target_file"

因错误而失败:

cat target/middle: Is a directory
cat : No such file or directory

cat 无法处理其中包含空格的文件路径。

我试过以下:

echo -e "Something New\n$(cat \"$target_file\")" > "$target_file"

不走运。

和解决方案?

bash file space
2个回答
1
投票

除了您的问题之外,在一个命令中读取和写入同一文件也可能会引发问题。以下是编写脚本的一种方式:

target_file="target/middle dir/filename"
{ echo "Something New"; cat "$target_file"; } > "$target_file".temp~ &&
        mv "$target_file".temp~ "$target_file"

另外,你不应该使用

echo -e
;它不可移植,对于您的情况,如果文件内容包含反斜杠字符(
-e
会尝试解释它们)可能会出现问题。


0
投票

最接近您的解决方案是:

echo -e "Something New\n$(cat "$target_file")" > "$target_file"

但是对我来说这个看起来更好:

echo -e "Something New\n`cat "$target_file"`" > "$target_file"

也可以使用sed(避免在命令中调用command):

sed -i '1iSomething New' "$target_file"
© www.soinside.com 2019 - 2024. All rights reserved.