I have alot of subdirectories structure with several mkv files.
I want to retrieve the biggest file by size, I managed to do with (test.sh):
$folder="$1"
m2ts=$(find "$folder" -type f -iname *.mkv -printf '%s %p\n' | sort -nr | head -1 | cut -d ' ' -f2)
echo $m2ts
All good until if folder might contain space like: /home/tester/This is a long path
If I do test:
find "/home/tester/This is a long path" -type f -iname *.mkv -printf '%s %p\n' | sort -nr | head -1 | cut -d ' ' -f2
It returns : /home/tester/This instead if biggest mkv path
What should I do ?
>Solution :
The issue is that by specifying cut -d ' ' you tell cut to split fields at every space character. So if your path contains a space, it will be cut off.
One simple solution would be:
$folder="$1"
m2ts=$(find "$folder" -type f -iname *.mkv -printf '%s\t%p\n' | sort -nr | head -1 | cut -f2-)
echo $m2ts
Note how printf '%s %p\n' was replaced with printf '%s\t%p\n',
which allows us to use the default field separator in cut (the tab character '\t').
Additionally, by specifying cut -f2- instead of cut -f2,
we get all fields after the size, not just up to the next field separator (\t). So even if the filepath would contain a tab, it would still work.
If some lunatic decides to use newlines in their file names this will still break, but at that point they just want to see the world burn :).