Skip to content
Advertisement

results of ls in one line when the output goes to a file

ls returns files in a line when it connects to stdout.

JavaScript

when it redirects to a file

JavaScript

I realize the option -C

JavaScript

However, when a list of files has many, ls puts carriage returns in the list. like

JavaScript

How can I have

JavaScript

Advertisement

Answer

I don’t know if ls provides an option for that and I haven’t looked it up. Since the question doesn’t specifically ask for a very fast or computationally efficient solution, I recommend to synthesize a command using ls and sed:

JavaScript

It takes the ls output and replaces all newlines n with spaces. The -z switch is required because otherwise sed would work line-oriented, and sed‘s pattern matcher would never see the n. You will have a problem if one of your filenames in $dir contains spaces.

If computational efficiency is a concern, I recommend searching for such an option (man ls) or writing a program that does just that (using, e.g., the C language).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement