Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I've been using the following command to list the ten largest files, at any depth, under the current directory:

find -type f -size +10M -exec ls -gGsSh1 {} + | awk 'NR<=10 {print $0}'

(I use awk instead of head to prevent a broken pipe error when the list is too long)

It works well, but it's evidently hard to remember and type every time. I tried putting this in .bash_aliases, but it doesn't work then (it prints 10 empty lines).

If I use less instead of awk, the output is presented correctly, but that means showing the whole list of files bigger than 10MB (my lower threshold), sorted by size, rather than only the top ones.

So, what's making awk choke as part of an aliased command here (assuming that's indeed the problem), and what can I do to fix it?

share|improve this question

1 Answer 1

up vote 7 down vote accepted

When using this command as an alias, $0 is no more protected by the single quotes and then converted to your shell name which happen to be an unset variable name, leading to the empty lines.

One way to protect $0 from shell expansion would be to use something like:

alias F="find -type f -size +1k -exec ls -gGsSh1 {} + | awk 'NR<=10 {print \\$0}'"

As this $0 is useless, you can just remove it from the awk statement.

find -type f -size +10M -exec ls -gGsSh1 {} + | awk 'NR<=10 {print}'

You can go further and remove the whole block as printing the line is awk default anyway:

find -type f -size +10M -exec ls -gGsSh1 {} + | awk 'NR<=10'

Alternatively, you can just keep using head and drop the error message

find -type f -size +10M -exec ls -gGsSh1 {} + 2>&1 | head
share|improve this answer
    
Works like a charm, thanks! Also, TIL a new awk trick :D (not that I knew many, though :P) –  waldyrious May 6 '13 at 12:00
1  
@jlliagre - actually $0 here is not a shell name as it is protected by ' and passed verbatim to awk. It denotes the whole line in shell (Change it to $1 and you'll see first record of line not first argument to shell). –  Maciej Piechotka May 6 '13 at 14:25
    
@MaciejPiechotka You are missing the point. $0 is definitely replaced by the shell name when the command is used as an alias. –  jlliagre May 6 '13 at 15:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.