LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   create script by spliting filenames (https://www.linuxquestions.org/questions/linux-newbie-8/create-script-by-spliting-filenames-899354/)

nicolasdiogo 08-25-2011 05:39 AM

create script by spliting filenames
 
hello (again!)


folks i am trying to write a bash script to restore some files from a bunch of archives.

the archive are named as follows:
Code:

ls
vzdump-qemu-201-2011_08_19-18_09_13.tgz
vzdump-qemu-202-2011_08_19-18_11_45.tgz
vzdump-qemu-203-2011_08_19-18_14_05.tgz
vzdump-qemu-3321-2011_08_19-18_16_37.tgz
vzdump-qemu-7501-2011_08_19-18_18_32.tgz
vzdump-qemu-99000-2011_08_19-18_31_24.tgz
vzdump-qemu-99101-2011_08_19-17_58_40.tgz
vzdump-qemu-99201-2011_08_19-18_01_07.tgz
vzdump-qemu-99501-2011_08_19-18_02_28.tgz

to run the tool that i need; i require to know the ID of this file.

for the first file (vzdump-qemu-201-2011_08_19-18_09_13.tgz)
this ID is 201

so i need to split/cut out the filename and get this ID for each file.


i have tried to find the solution - but i have not found many articles that described what they were doing - and instead i found a lot of pieces of bash coding that did something that i did not understand.

many thanks,

markush 08-25-2011 06:04 AM

Hello nicolasdiogo,

I'd use Perl for this:
Code:

#!/usr/bin/perl

use strict;
use warnings;

opendir(TGZFILES, ".") or die "doesn't work $!\n";
my @file;
while (readdir TGZFILES) {
  if ($_ =~ m/\.tgz/) {
      @file = split "-", $_;
      print "id: ", $file[2], "  filename: ", $_, "\n";
  }
}

Markus

rodrifra 08-25-2011 06:39 AM

For me awk is the God, so here is my solution (acording to the name format you have provided).

ls vz*|awk '{print substr($1,13,length($1)-36)}'

chickenjoy 08-25-2011 06:52 AM

just to help clarify for everyone: is the ID always the first 3 digits? or the numbers in between the 2nd dash and the 3rd dash? (ex: 99501 for the last file)

grail 08-25-2011 07:24 AM

I think it depends what else you might need to do, but if you were to use ls and awk as suggested by rodrifra, I think this would be easier:
Code:

ls vz* | awk -F- '{print "ID:",$3}'
If it is a script your after to also do other things, bash could also give it a whirl:
Code:

for file in vz*
do
    set -- ${file//-/ }
    echo "ID: $3"
done


rodrifra 08-25-2011 08:41 AM

Not only easier, it is much better your way grail.

Regards.

chrism01 08-26-2011 01:34 AM

Code:

for file in vz*
do
    echo $file | cut -d'-' -f3
done


nicolasdiogo 08-26-2011 05:03 AM

thanks a lot Chris,

i finished the script using your suggestion many thanks

chrism01 08-28-2011 08:19 PM

No worries; glad I could help :)


All times are GMT -5. The time now is 11:20 AM.