How do I list one filename per output line in Linux?

Viewed 214568

I'm using ls -a command to get the file names in a directory, but the output is in a single line.

Like this:

.  ..  .bash_history  .ssh  updater_error_log.txt

I need a built-in alternative to get filenames, each on a new line, like this:

.  
..  
.bash_history  
.ssh  
updater_error_log.txt
8 Answers

You can also use ls -w1

This allows to set number of columns. From manpage of ls:

   -w, --width=COLS
          set output width to COLS.  0 means no limit

Easy, as long as your filenames don't include newlines:

find . -maxdepth 1

If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):

find . -maxdepth 1 -print0

Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort's -z. Your own script similarly would need to account for this.

-1 switch is the obvious way of doing it but just to mention, another option is using echo and a command substitution within a double quote which retains the white-spaces(here \n):

echo "$(ls)"

Also how ls command behaves is mentioned here:

If standard output is a terminal, the output is in columns (sorted vertically) and control characters are output as question marks; otherwise, the output is listed one per line and control characters are output as-is.

Now you see why redirecting or piping outputs one per line.

Related