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}')
alphabet122
  • 3
  • 1
  • 5

3 Answers3

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.

Stephen Kitt
  • 434,908
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.

user1404316
  • 3,078
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.

Stephen Kitt
  • 434,908
alpha
  • 1,994