Reputation: 30990
I need to bash script to tar half of the files in a directory. The files are .gz files with the naming convention x.gz where x is a number starting from 1 and ends with 100, I need to tar the first half of the files. How do I do this?
Upvotes: 2
Views: 3689
Reputation: 1
Here's one way to do this (using KSH which should be available anywhere BASH is)
save below script in x.sh and chmod +x x.sh; then run it
#!/bin/ksh
#
#
## first create 100 dummy GZ files
##
x=0
while :
do
x=$((${x}+1));
if [ x -gt 100 ]; then
break;
fi
touch ${x}.gz;
done
## next parse the list, sort it and loop tar it stopping at 50.gz
##
for x in `ls *.gz | sed 's/\.gz//g' | sort -n`
do
if [ $x -gt 50 ]; then
exit 0;
fi
tar -rvf all-50.tar ${x}.gz
done
Upvotes: -1
Reputation: 715
I understand that you have an arbitrary number of files named x.gz in the current directory. You want to tar half of them.
But as you see from the answers, your description is not detailed enough.
I tried to provide the most flexible.
files=`find . -maxdepth 1 -mindepth 1 -type f -printf '%f\n'|grep -P '^\d+.gz$'|sort -n`
n=`echo $files|sed "s/ /\n/g"|wc -l`
half=$(( $n / 2 ))
d=`echo $files|sed "s/ /\n/g"|head -$half`
tar czf archive.tar.gz $d
Upvotes: 0
Reputation: 40688
Your question is a little unclear. I assume you have x.gz and you want to add 1.gz to 50.gz into a tar file. If that is the case:
tar cjf MyArchive.tar.bz2 {1..50}.gz
The above command will put the first 50 .gz files into an archive named MyArchive.tar.bz2
Upvotes: 6