Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get highest file path by size in bash where path contains space

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading