如何根据第一个字符从文件列表中复制

How to copy from list of files based on first character

我有需要根据第一个字符从列表中复制文件的要求。如果您看到下面的列表文件中有三行,我需要将以 M 和 A 开头的行复制到新位置,例如 (destination/testfolder) 以及文件夹结构。代码还必须支持空格。任何帮助将不胜感激。

cat /tmp/patchfiles.txt
M       Hyperion/Planning/AAAAA/Planning/HP-AAAAA/info plan/listing.xml
A       Hyperion/Planning/AAAAA/Planning/Import.xml
D       Hyperion/Planning/AAAAA/Planning/HP-AAAAA/Import.xml

一个简单的 while read 循环就足够了:

while read -r status file; do
    case $status in
        M|A)
            cp "$file" /path/to/destination
            ;;
    esac
done < /tmp/patchfiles.txt

这会从您的文件中读取每一行,将第一个字段存储在变量 $status 中,其余字段存储在 $file 中。如果 $status 是 "M" 或 "A",则文件被复制到目的地。

如果您的系统上有 dirname,您可以很容易地创建目录结构,如下所示:

dir="/path/to/destination/$(dirname "$file")"
mkdir -p "$dir" && cp "$file" "$dir"

否则,您可以像这样使用 bash:

dir="/path/to/destination/${file%/*}"
mkdir -p "$dir" && cp "$file" "$dir"

这使用 bash 内置字符串操作 trim 文件名中最后一个 /.

之后的部分