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.

$ ls
a b c

when it redirects to a file

$ ls > foo.txt
$ cat foo.txt
a
b
c

I realize the option -C

$ ls -C > hoge.txt
$ cat hoge.txt
a b c

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

 a b c d e f g h
 i j k l ....

How can I have

 a b c d e f g h i j k l.....(without n)

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:

ls "$dir" | sed -z 's/n/ /g'

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