How to line up the ls -l list of files and directories in a column instead of printing horizontally?

7,315

Solution 1

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.

Solution 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.

Share:
7,315

Related videos on Youtube

alphabet122
Author by

alphabet122

Updated on September 18, 2022

Comments

  • alphabet122
    alphabet122 almost 2 years

    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}')
    
    • Jeff Schaller
      Jeff Schaller over 6 years
      are you on a Linux system that has the stat command? Also, try the ls -1 (number one) option.
    • alphabet122
      alphabet122 over 6 years
      Jeff, I am not sure. I use Terminal on Mac.
    • Angel Todorov
      Angel Todorov over 6 years
    • Angel Todorov
      Angel Todorov over 6 years
      The actual answer to your question is that you did not quote the command substitution, so word splitting happens which converts newlines to spaces.
  • Angel Todorov
    Angel Todorov over 6 years
    Or with GNU stat: stat -c '%n:%A' * | sed ...
  • user1404316
    user1404316 over 6 years
    @glennjackman - nicer than mine!