Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all files and separate results by comma on Unix?

Tags:

bash

shell

unix

I would like to go from the standard find output which is:

path/to/file1.yaml
path/to/file2.yaml
path/to/file3.yaml

To this:

path/to/file1.yaml,path/to/file2.yaml,path/to/file3.yaml

What's the simplest way to do that from the command line?

I have tried these things:

find . -path '*.yaml' | sed -e 's/\s/,/g'
find . -path '*.yaml' -print0 | sed -e 's/ /,/g'

but doesn't seem to work.

like image 624
Lance Avatar asked Mar 16 '15 17:03

Lance


3 Answers

Here is one approach for separating the filenames with commas:

find . -path '*.yaml' | tr '\n' ','

If the file names do not contain white space, then another approach is:

IFS=, echo $(find . -path '*.yaml')

In the comments, Kojiro suggests a third approach which preserves whitespace:

find . -path '*.yaml' -print0 | tr '\0' ,

Because newlines and commas are allowed in file names, this format may lead to confusion. This format should only be used if you know that your files are sensibly named.

like image 158
John1024 Avatar answered Nov 18 '22 16:11

John1024


This will work too :

  find . -path '*.yaml' | paste -s -d ',' -
like image 41
souser Avatar answered Nov 18 '22 17:11

souser


both python and perl can do it in one line:

python:

find . -path '*.yaml' | python -c 'import sys; print ",".join(sys.stdin.readlines())'

perl:

find . -path '*.yaml' | perl -e 'print join ",", map {chomp;$_} <STDIN>'
like image 3
Jason Hu Avatar answered Nov 18 '22 18:11

Jason Hu