I searched through the site and found nothing like what I needed, so I decided to make my own question.
I am using linux, trying to figure out a way to do what I described using tools like find, awk, rm, and others; but so far I have not been able to think of a way.
A bit of background,
- The files are renamed in a neat alphabetical manner. No white space.
- Subfolders are named like that too.
- When I say last file, I mean the last file by alphabetical sorting.
- The amount of files in each subfolder is not same. Some subfolders have 56 files, while others don't even hit two digit. So I can't execute a convenient command like this:
rm ./folder-*/020.jpg
Which I would have been able to if all subfolders had the same amount of files in them.
To illustrate the directory, it would be like
./original-folder
./original-folder/subfolder-001/001.jpg
./original-folder/subfolder-001/002.jpg
./original-folder/subfolder-001/003.jpg
./original-folder/subfolder-002/001.jpg
./original-folder/subfolder-002/002.jpg
./original-folder/subfolder-003/001.jpg
And so on. I want it to look like this basically
./original-folder
./original-folder/subfolder-001/001.jpg
./original-folder/subfolder-001/002.jpg
./original-folder/subfolder-002/001.jpg
./original-folder/subfolder-003/001.jpg
Note that last file is one less than before.
My solution was to find a way to start a list every time the program went to a new folder, and then borrowing the last item of that list for rm command but I have absolutely 0 idea on how to do that within bash or anything.
Feels like I need a fully functional programming language to do that.
CodePudding user response:
Given your input files are named in a sortable way and don't contain any spaces as shownin the example in your question:
$ cat tst.sh
#!/usr/bin/env bash
find ./original-folder -type f |
sort |
awk '
{
dir = $0
sub("/[^/] $","",dir)
}
dir != prev {
prt()
numFiles = 0
prev = dir
}
{ files[ numFiles] = $0 }
END { prt() }
function prt( fileNr, endNr) {
endNr = numFiles - ( numFiles == 1 ? 0 : 1 )
for ( fileNr=1; fileNr <= endNr; fileNr ) {
print files[fileNr]
}
}
' |
xargs -I {} echo rm -- '{}'
$ ./tst.sh
rm -- ./original-folder/subfolder-001/001.jpg
rm -- ./original-folder/subfolder-001/002.jpg
rm -- ./original-folder/subfolder-002/001.jpg
rm -- ./original-folder/subfolder-003/001.jpg
Remove the echo
once you've initially tested and are happy with the result. The sort
may not be necessary depending on whatever order find
outputs it's results but it won't hurt.
CodePudding user response:
Assuming you can create files on the directory this method worked for me:
#!/bin/bash
originalFolder=/path/to/your/directory/containing/orignal-folder
ls $originalFolder > folder_list.txt
while read -r line; do
ls -r $originalFolder/$line > file_list.txt
fileLength=`wc -l < file_list.txt`
if [ $fileLength -gt 1 ]
then
rmFile=`head -n 1 file_list.txt`
rm $originalFolder/$line/$rmFile
fi
done < folder_list.txt