tags:

views:

284

answers:

6

I would like to join the result of ls -1 into one line and delimit it with whatever i want.

Are there any standard linux commands i can use to achieve this?

+2  A: 

If you version of xargs supports the -d flag then this should work

ls  | xargs -d, -L 1 echo

-d is the delimiter flag

If you do not have -d, then you can try the following

ls | xargs -I {} echo {}, | xargs echo

The first xargs allows you to specify your delimiter which is a comma in this example.

Chris J
+5  A: 

EDIT: If your delimiter is a comma then the following also works ls -m

Ah, the power and simplicity !

ls -1 | tr "\\n" ","

Change the "," to whatever you want.

zaf
+1, but a more elaborate version should handle last \n differently
mouviciel
If the file name contains a `\n` in it, this will replace that too.
codaddict
@unicornaddict you can use -b or -q for ls to handle strange cases like you mention.
zaf
@mouviciel that would be a nice touch.
zaf
A: 

You can use:

ls -1 | perl -pe 's/\n$/some_delimiter/'
codaddict
+2  A: 

To avoid potential newline confusion for tr we could add the -b flag to ls:

ls -1b | tr '\n' ';'
yabt
This is also a great solution.
JavaRocky
A: 

This replaces the last comma with a newline:

ls -1 | tr '\n' ',' | sed 's/,$/\n/'

ls -m includes newlines at the screen-width character (80th for example).

Mostly Bash (only ls is external):

files=($(ls -1))
list=${files[@]/%/,}
list=${list%*,}
Dennis Williamson
+1  A: 

just bash

mystring=$(printf "%s|" *)
echo ${mystring%|}
ghostdog74
Slightly more efficient would be to use "printf -v mystring "%s|" *" - that avoids a fork for the $()
camh