Skip to content
Advertisement

Save only one string of multi-string command output

I’ve got a bash command to find the largest file in a sub-directory. I’d like to save the output to a variable to use it with other commands.

bigile=$(find /path/to/directory -type f -exec du -Sh {} + | sort -rh | head -n 1)

Unfortunately, this saves both the file size and the filepath.

echo $file
216K /path/to/directory/bigfile

If I pass the variable to commands take that a file as input, I see an error:

wc -lm $file
wc: cannot access '216K': No such file or directory
6333 217649 /home/path/to/directory/bigfile

Obviously, I get the output I need, but I don’t want the error message. How can I save only the first string of the find command output?

Thanks!!!

Advertisement

Answer

Could you please try following and let me know if this helps you.

bigile=$(find /path/to/directory -type f -exec du -Sh {} + | sort -rh | awk 'FNR==1{print $2}')

Explanation: Simply added awk after sort command and there FNR==1 condition will make sure that very first line only is getting picked up then printing the 2nd field of that line too.

Advertisement