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.

  • Could you use simpler file name examples? Sep 3, 2016 at 1:42

2 Answers 2


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') )


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=( ${TAG1//_/ } )
TAG2=( ${TAG2//_/ } )

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .