0

I'm trying to print the names of each file and directory for the current user, but it keeps printing in one big long line. I want to have each file present as a column, just as it does when I print ls -l.

You don't have to help with this, but for better context, I'm trying to make sure a colon ':' shows up after each file name, along with its group permissions from the first field. For example, it could look like "file/dir:---" or "file/dir:r--"

echo $(ls -l /home/$(whoami) | awk '{if (NR>1) print $9}'): $(ls -l /home/$(whoami) | awk '{if (NR>1) print $1}')
  • 1
    are you on a Linux system that has the stat command? Also, try the ls -1 (number one) option. – Jeff Schaller Feb 14 '18 at 15:15
  • Jeff, I am not sure. I use Terminal on Mac. – alphabet122 Feb 14 '18 at 15:17
  • don't parse ls – glenn jackman Feb 14 '18 at 16:41
  • The actual answer to your question is that you did not quote the command substitution, so word splitting happens which converts newlines to spaces. – glenn jackman Feb 14 '18 at 16:51
3
ls -1

will list one file per line. This is the default when ls’s output is redirected anywhere that’s not a terminal.

To get the output you’re after, you’d be better off doing something like

ls -l | awk 'NR > 1 { print $9 ":" $1 }'

or better still,

stat -c "%n:%A" *

although both of these list all the permissions, not just the group permissions. To only see group permissions, use

ls -l | awk 'NR > 1 { print $9 ":" substr($1,5,3) }'

or

stat -c "%n:%A" * | sed 's/....\(...\)...$/\1/'

(hat-tip to user1404316 for the sed expression).

The ls-parsing variants don’t cope with spaces and other blank characters in file names, so they shouldn’t be used in general.

2

There is a much simpler solution if you have access to a version of find that includes the GNU extensions. In order to find out, run man find and search for the -printf (To do that first press /^ *-printf). If you do, you are in luck, because your solution could be:

find . -maxdepth 1 -type f -printf "%f: %M\n" | sed 's/....\(...\)...$/\1/'

As a bonus, this answer will work in the unusual case of a file name including the colon character.

  • 2
    Or with GNU stat: stat -c '%n:%A' * | sed ... – glenn jackman Feb 14 '18 at 16:47
  • @glennjackman - nicer than mine! – user1404316 Feb 14 '18 at 17:49
0

If you wanted the files for only the current user.

ls -l | awk -v var="$(whoami)" '$4 == var {print $9}'

That will only print files that belong to the current user, in the format you require.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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