linux - 查找文件并对其名称中包含尾随或前导空格进行 tar

标签 linux bash tar

我有一个脚本,尝试使用 tar 归档目录的内容:

#!/bin/bash

find /root/files -type f -name "1*" -print0 | while read -d $'\0' file
do
    MYDIRNAME=$(dirname "${file}")
    MYFILENAME=$(basename "${file}")
    MYMODIFYDIR=$(echo "$MYDIRNAME" | sed 's/^\///' | sed 's/\//_/g' | sed 's/\ /_/g')
    MYMODIFYFILENAME=$(echo "$MYFILENAME" | sed 's/\//_/g' | sed 's/\ /_/g')
    GZIP=-9 tar -zcvf /root/"$MYMODIFYDIR"_"$MYMODIFYFILENAME".tar.gz "$file"
done

它不适用于名称中带有前导或尾随空格的文件。到达文件 /root/files/tetst\test\tgdjd/1\5765765\565765\ 时发生错误(注意文件名中的尾随空格):

tar: /root/files/tetst test tgdjd/1 5765765 565765: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

tar 给出的错误已从文件名中修剪尾随空格。

最佳答案

您忘记在 while 循环中重置 IFS,因此前导和尾随空格将被视为分隔符。使用这个:

find /root/files -type f -name "1*" -print0 | while IFS= read -d $'\0' file

您还可以添加 -r 来读取文件名中是否可以包含反斜杠。

请参阅此处,了解有关 readIFS 的更全面说明:https://stackoverflow.com/a/26480210/1262699

关于linux - 查找文件并对其名称中包含尾随或前导空格进行 tar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30214151/

相关文章:

c - 为什么 c 中的时间函数返回毫秒而不是秒?

linux - 在处理命令输出中的空列时获取第 6 列

Bash 和文件命令样本大小

python - 处理 sshpass 密码字段中的特殊字符

bash - 从具有重复条目名称的 tar 文件中提取

rust - 如何在下载过程中解压缩和解压 tar.gz 存档?

python - 使用 chmod +x python 将文件添加到 tar

regex - 如何在 zgrep/zcat 命令中指定正则表达式?

linux - linux 中的整个系统空间地址空间是否真的不使用请求分页?

bash - 理解(多重和自动)文件名引用