【问题标题】:How to untar specific files from a number of tar files and zip them?如何从多个 tar 文件中解压缩特定文件并压缩它们?
【发布时间】:2013-08-30 03:19:24
【问题描述】:

要求是从多个 tar 中提取所有 *.properties 文件并将它们放入一个 zip 中。

我试过这个:

 find . -iwholename "*/ext*/*.tar.gz"|xargs -n 1 tar --wildcards '*.properties'  -xvzf | zip -@ tar-properties.zip

这是使用所有 tar 中的 .properties 文件创建一个 zip。

但问题是 tar 的结构是因为每个 tar 都包含一个包含文件的属性文件夹。上面的命令正在创建一个包含所有文件的单个属性文件夹的 zip。

有没有办法将这些文件放入 zip 中,其文件夹结构类似于 {name of the tar}/properties/*.properties ?

【问题讨论】:

    标签: bash zip tar


    【解决方案1】:

    你可以使用这个脚本。我的解决方案也使用--transform。请先检查您的tar 命令是否支持tar --help 2>&1 | grep -Fe --transform

    #!/bin/bash
    
    [ -n "$BASH_VERSION" ] || {
        echo "You need bash to run this script." >&2
        exit 1
    }
    
    TEMPDIR=/tmp/properties-files
    OUTPUTFILE=$PWD/tar-properties.zip  ## Must be an absolute path.
    
    IFS=
    
    if [[ ! -d $TEMPDIR ]]; then
        mkdir -p "$TEMPDIR" || {
            echo "Unable to create temporary directory $TEMPDIR." >&2
            exit 1
        }
    fi
    
    NAMES=()
    
    while read -r FILE; do
        NAMEOFTAR=${FILE##*/}  ## Remove dir part.
        NAMEOFTAR=${NAMEOFTAR%.tar.gz} to remove extension  ## Remove .tar.gz.
    
        echo "Extracting $FILE."
    
        tar --wildcards '*.properties' -xvzf "$FILE" -C "$TEMPDIR" --transform "s@.*/@${NAMEOFTAR//@/\\@}/properties/@" || {
            echo "An error occurred extracting to $TEMPDIR." >&2
            exit 1
        }
    
        NAMES+=("$NAMEOFTAR")
    done < <(exec find . -type f -iwholename '*/ext*/*.tar.gz')
    
    (
        cd "$TEMPDIR" >/dev/null || {
            echo "Unable to change directory to $TEMPDIR."
            exit 1
        }
    
        zip -a "$OUTPUTFILE" "${NAMES[@]}"
    )
    

    将其保存到脚本中,然后在要搜索这些文件的目录中运行它

    bash /path/to/script.sh`
    

    【讨论】:

      【解决方案2】:

      您可以使用tar 选项--transform, --xform 来解决问题。由于sed 表达式,此选项允许操作路径。

      find . -iwholename "*/ext*/*.tar.gz"|xargs -n 1 tar --wildcards '*.properties'  -xvzf --xform 's#.*/#name_of_the_tar/properties/#' | zip -@ tar-properties.zip
      

      【讨论】:

        猜你喜欢
        • 2019-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-10
        • 2011-03-21
        • 1970-01-01
        相关资源
        最近更新 更多