1

I got a lot of files with the following format:

2014_04_01_11.txt
2014_04_01_12.txt
2014_04_01_13.txt
2013_03_25_12.txt
2013_04_29_15.txt

I would like to tar all theses files into an archive 20?? _ ?? _ ??**.tar.gz.

My actual command is:

find . -name '????_??_??_*.txt' | tar ...

I don't know how to define dynamically the name of the archive.

  • Ok, now this question just doesn't make sense. Do you want one archive per file or do you have multiple dates and you want and archive for each date as per your comment below. – Graeme Apr 9 '14 at 17:25
  • @Graeme I have multiple files (year)_(month)_(day)_(hour) and i would like to TAR all these files into an archive (year)_(month)_(day) – Greg Apr 9 '14 at 17:29
  • @Graeme, He has multiple files per date. so the question makes sense :-) – Slyx Apr 9 '14 at 17:29
2

This is very simple:

tar -cvzf 2014_04_01.tar.gz 2014_04_01_??.txt

Update

To do this for multiple dates (GNU find):

find . -maxdepth 1 -name '????_??_??_??.txt' |
  cut -d_ -f 1-3 |
  sort -u |
  while read date; do
    tar -cvzf "$date".tar.gz "$date"_??.txt
  done
  • I have also 2013_01_01, 2014_04_25, etc... – Greg Apr 9 '14 at 17:17
  • @Greg, updated. – Graeme Apr 9 '14 at 17:38
0

I suggest you the following bash script :

#!/bin/bash
FIRST=1
unset TARFILE
unset FILESET
find . -name '????_??_??_*.txt' | sort | while read fn
    do
    CURTARFILE=`echo $(basename $fn)|awk -F_ '{print $1"_"$2"_"$3".tar.gz"}'`
    if [ "$CURTARFILE" == "$TARFILE"] ; then
        FILESET=$FILESET" \"$fn\""
        FIRST=0
        continue
    fi
    [ "$FIRST" == "0" ] && tar cfz $TARFILE $FILESET
    $FILESET="\"$fn\""
    FIRST=0
    TARFILE=$CURTARFILE
done
  • @Greg Are your TXT files stored in the same directory? – Slyx Apr 9 '14 at 17:32
  • Yes, they could be... (customer)/(year)_(month)_(day)_(hour). However, @Graeme solution works. – Greg Apr 9 '14 at 17:39
  • That's why Graeme solution is better, i upvote it :-) – Slyx Apr 9 '14 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.