Home > other >  Sort files based on filename into folders and concat files within each folder based on folder name
Sort files based on filename into folders and concat files within each folder based on folder name

Time:11-05

Any help would be VERY appreciated! I have hundreds of video files named in the following format (see below). The first 4 characters are random, but there is always 4. 3000 is always there.

Can someone please help me create folders based on the center of the filename (ie 000, 001, 002, 003 and so on).

Then concatenate all the files in each of the folders using ffmpeg in order in their filename. 0000.ts, 0001.ts, 0002.ts and so on to a file named 000merged.ts, 001merged.ts, 002merged.ts and so on...

Example list of files located in a folder on the desktop.

1e98_3000_000_000_0000.ts

1e98_3000_000_000_0001.ts

1e98_3000_000_000_0002.ts

1e98_3000_000_000_0003.ts

d82j_3000_001_000_0000.ts

d82j_3000_001_000_0001.ts

d82j_3000_001_000_0002.ts

d82j_3000_001_000_0003.ts

a03l_3000_002_000_0000.ts

a03l_3000_002_000_0001.ts

a03l_3000_002_000_0002.ts

a03l_3000_002_000_0003.ts

This image shows the desired result.
enter image description here

CodePudding user response:

mkdir /tmp/test && cd $_            #or  cd ~/Desktop
echo A > 1e98_3000_000_000_0000.ts  #create some small test files
echo B > 1e98_3000_000_000_0001.ts
echo C > 1e98_3000_000_000_0002.ts
echo D > 1e98_3000_000_000_0003.ts
echo E > d82j_3000_001_000_0000.ts
echo F > d82j_3000_001_000_0001.ts
echo G > d82j_3000_001_000_0002.ts
echo H > d82j_3000_001_000_0003.ts
echo I > a03l_3000_002_000_0000.ts
echo J > a03l_3000_002_000_0001.ts
echo K > a03l_3000_002_000_0002.ts
echo L > a03l_3000_002_000_0003.ts
# mkdir and copy each *.ts into its dir plus rename file:
perl -E'/^...._3000_(...)_..._(....\.ts)$/&&qx(mkdir -p $1;cp -p $_ $1/$2)for@ARGV' *.ts
ls -rtl
find ??? -type f -ls
for dir in ???;do cat $dir/????.ts > $dir/${dir}merged.ts; done
ls -rtl */*merged.ts

Cleanup test:

rm -rf /tmp/test/???     #cleanup new dirs with files
rm -rf /tmp/test         #cleanup all
  • Related