kensuke1984
kensuke1984

Reputation: 995

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)

Upvotes: 2

Views: 1082

Answers (3)

Nitish
Nitish

Reputation: 607

Try the below solution,

echo -E $(ls -1 dir) > file.txt

where

-1 print o/p in single-column

-E disable interpretation of backslash escapes

Source: this serverfault page

Upvotes: 1

Brad Pitt
Brad Pitt

Reputation: 416

This will do the trick:

ls | xargs > foo.txt

Upvotes: 1

pasbi
pasbi

Reputation: 2179

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

Upvotes: 2

Related Questions