Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to use a part of the file name to be inserted into a new file created using the script. For eg: dcn_2014_01_31_14_17_45_505.pcap and dcn_2014_01_31_14_32_27_656.pcap should give 2014_0131_1417_to_1432_utc.pcap. I can get it up to dcn_2014_01_31_14_17_45_505_to_dcn_2014_01_31_14_32_27_656.pcap . How do I select each number so as to get the desired output? I have used the following script:

TAG1=$(basename ${FILES[0]} | sed 's/.pcap//')
TAG2=$(basename ${FILES[$N-1]} | sed 's/.pcap//')

#merge the files
mergecap -w /mnt/md0/capture/DCN/"${TAG1}_to_${TAG2}".pcap ${FILES[@]}

Where FILES[] is an array of 15 files.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

For modern versions of bash, you can use an array to store the different parts of the filename. Something like:

TAG1=( $(basename "${FILES[0]}" | sed 's/_/ /g') )
TAG2=( $(basename "${FILES[$N-1]}" | sed 's/_/ /g') )

range="${TAG1[1]}_${TAG1[2]}${TAG1[3]}_${TAG1[4]}${TAG1[5]}_to_${TAG2[4]}${TAG2[5]}"

echo "$range"
#mergecap -w /mnt/md0/capture/DCN/"$range"_utc.pcap ${FILES[@]}

You can also use bash to get the basename and do the substitution:

TAG1="${FILES[0]##*/}"
TAG1=( ${TAG1//_/ } )
TAG2="${FILES[$N-1]##*/}"
TAG2=( ${TAG2//_/ } )
share|improve this answer

This kind of thing is easier to do with Perl's regex and captures:

$filename =~ /dcn_(\d{4})_(\d{2})_(\d{2})_(\d{2})_(\d{2}).*\.pcap/;
my $year = $1;
my $month = $2;
my $day = $3;
my $hour = $4;
my $minute = $5;

Then you just do the same for the other file and format the output filename however you want.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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