Take the 2-minute tour ×

I'm wondering what is the syntax error in my command I'm using.

In the current directory I use the command ls -l to retrieve file permissions in my directory.

How would I do a query to see which files are readable, writeable, and executable by the user and then print a filtered list using awk?

I know the bits I'm interested in are the second, third, and fourth.

For example,

-rw-r----- .. .. .. ..


drw-r----- .. .. .. ..

I have an awk command as follows:

ls -l | awk '{if{$1 == /.rwx....../}print "line"}'

I've tried many things but there's still a syntax error.

Any help is greatly appreciated! Thanks in advance!

share|improve this question
If your system has stat you should use that instead of parsing ls. Also, if your find supports it, try find -perms u=rw -type f or other permissions such as u=rwx, -g=x or /u=w,g=w. See man find for information on the meaning of these patterns. –  Dennis Williamson May 21 '12 at 1:51
add comment

2 Answers

up vote 3 down vote accepted

The operator used to check if a string matches a regular expression is ~, not ==. Also, use () around the condition in the if statement:

ls -l | awk '{ if ($1 ~ /.rwx....../) print "line" }' 
share|improve this answer
Ah, noted, I made a typo in the question. Even as ~ it still gives me a syntax error. But the brackets. That was the problem. Thank you so much for your help! –  tf.rz May 20 '12 at 21:30
Sadly I need to wait 9 minutes. But thank you! :) –  tf.rz May 20 '12 at 21:30
add comment

I agree with Dennis; it's best to avoid piping ls and if you're going to do something, you may as well do it properly using stat:

stat -c '%A %N' * | awk '/^-rwx/ { print $2 }' | sed "s%^.\(.*\).$%\1%"

or just in awk:

stat -c '%A %N' * | awk '/^-rwx/ { print substr ($2, 2, length ($2) - 2) }'


The above fails with files containing spaces (sorry). This considers spaces and newline chars:

stat -c '%A %N' * | awk '/^-rwx/ {print substr($0, 13, length($0) - 13) }'

share|improve this answer
The problem with using $2 is that it fails for files with spaces in their names. This might be better: stat -c '%A %N' * | awk '/^-rwx/ {print substr($0, 13, length($0) - 13) }' (or you could use %n and print substr($0, 12) ) –  Dennis Williamson May 21 '12 at 5:20
@DennisWilliamson Ahh yes my one liner fails to find files with spaces in them. Also, I think %n fails with files containing newline chars: \n gets expanded? –  Steve May 21 '12 at 5:52
add comment

Your Answer


