【问题标题】:Exracting 200 first lines from a zip file and creating this file into a different folder从 zip 文件中提取 200 行第一行并将此文件创建到不同的文件夹中
【发布时间】:2021-01-26 04:37:06
【问题描述】:

我有一个名为 /home/myusername/originalFiles 的文件夹,其中有大量 *.gz 大文件。在这个文件夹及其子文件夹中,我们也有大量的 *.gz 大文件。无需删除或修改我需要的任何 *.gz 文件:

a) 对于 /home/myusername/originalFiles(和子文件夹)中的每个文件 f,展开它,

b) 从展开的 f 中提取前 200 行

c) 将 b) 中的“200 行”文件再次转换为 gz 文件

d) 将 c) 中的“gzipped 200 行”文件复制到另一个名为 /home/myusername/newSampleFiles 的文件夹中,但要遵守 /home/myusername/originalFiles 中的文件夹结构和名称。因此,如果原始文件 f 位于 /home/myusername/originalFiles/year2020 之类的子文件夹中,则 c) 中相应的“gzipped 200 行”文件必须位于 /home/myusername/newSampleFiles/year2020 中并使用相同的名称和扩展名/home/myusername/originalFiles 中的原始文件

e) 不要保留在 a) 中获得的任何扩展文件

f) 仅使用 Linux cmds 执行此操作

我试过了

找到 . -type f -name "*.gz" -print | xargs -I@ sh -c 'head -n200 @> /home/myusername/newSampleFiles/@'

但我收到了错误消息:

/home/myusername/newSampleFiles/./someFile.txt.gz: 没有这样的文件或目录

【问题讨论】:

    标签: linux bash centos gzip


    【解决方案1】:
    while read file;
    do
        file2="${file%.*}"
        gzip -cd "$file" | head -n200 > "/home/myusername/newSampleFiles$file2";
        gzip -c "/home/myusername/newSampleFiles$file2" > "/home/myusername/newSampleFiles$file"
     done <<< "$(find /path/to/dir -type f -name "*.gz")"
    

    将 find 命令重定向到 while 循环中,将输出的每一行读取到变量文件中,然后使用参数扩展从 file1 中剥离任何文件扩展名并将结果读取到 file2 中。然后在 gzip 命令中使用这些变量。

    【讨论】:

    • 我使用您提供的命令创建了一个 sh 脚本,但是如果我尝试解压缩新创建的 gz 文件,我会得到“不是 gzip 格式”。此外,originalFiles 文件夹中的文件夹结构也不受尊重。
    • 好的。我已经修改了解决方案。主要问题是您必须在 find 命令中使用完整路径,而不仅仅是相对路径(。)我还添加了带头文件的压缩。
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2021-05-16
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多