How to send list of file in a folder to a txt file in Linux

131,045

Solution 1

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

Solution 2

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt
Share:
131,045

Related videos on Youtube

alchemical
Author by

alchemical

Thus have I heard: Premature optimization is the root of all evil.

Updated on November 06, 2020

Comments

  • alchemical
    alchemical over 3 years

    I'm fairly new to Linux (CentOS in this case). I have a folder with about 2000 files in it. I'd like to ideally execute a command at the command prompt that would write out the name of all the files into a single txt file.

    If I have to, I could write an actual program to do it too, I was just thinking there might be a way to simply do it from the command prompt.

    • John La Rooy
      John La Rooy over 13 years
      Be careful with this, it's possible for filenames to contain all sorts of tricky characters. eg. newline
  • JohnAllen
    JohnAllen about 8 years
    Thankfully I googled this before writing a little bash script!
  • Vicky Dev
    Vicky Dev almost 8 years
    How to ignore certain files like backup files (files having "~" as suffix in their names) ?
  • usta
    usta almost 8 years
    @VickyDev One way would be to filter find's output through grep: find ~/docs -type f -maxdepth 1 | grep -v '~$' > filenames.txt
  • usta
    usta almost 8 years
    @VickyDev A cleaner way is to use find's -name with -not: find ~/docs -type f -maxdepth 1 -not -name '*~' > filenames.txt
  • usta
    usta almost 8 years
    @VickyDev Please have a look at stackoverflow.com/questions/1341467/… for more on the topic
  • Prince Patel
    Prince Patel almost 7 years
    For absolute path printf '%s\n' "$PWD"/* >filenames.txt
  • tripleee
    tripleee over 6 years
    For anything beyond this trivial use, you should probably avoid ls. See mywiki.wooledge.org/ParsingLs
  • kRazzy R
    kRazzy R over 6 years
    What if I want to save the each filename in a double quote " " and each such "" separated by a comma? Please tell how to do that. i.e if file names are a,b,c,d,e; I want them to be saved to a text file as "a","b","c","d","e"