Search code examples
filebashshellunixls

How can I save all filenames in a directory to a text file in bash?


I have a directory with millions of files. I've just learned millions are orphaned and I need to unlink them. I'd like to start with an array of all files in a single text file (csv ideally). Can you help?

I was going to do an ls and just save the terminal output to a file, but I figure there's a more elegant way.

How can I make something like ls > log.csv end up looking like

file1.txt,file2.txt, ... fileN.txt?


Solution

  • Try doing this :

    printf '%s\n' *.txt | paste -sd "," - > log.csv
    

    or

    printf '%s,' *.txt > log.csv
    

    or

    printf '"%s",' *.txt > log.csv
    

    if you have special characters like spaces in filenames.