56

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.

fmark
  • 57,259
  • 27
  • 100
  • 107
alchemical
  • 13,559
  • 23
  • 83
  • 110

2 Answers2

114

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

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • Thankfully I googled this before writing a little bash script! – JohnAllen Feb 26 '16 at 04:38
  • 8
    For absolute path `printf '%s\n' "$PWD"/* >filenames.txt` – Prince Patel Jun 06 '17 at 12:38
  • For anything beyond this trivial use, you should probably avoid `ls`. See http://mywiki.wooledge.org/ParsingLs – tripleee Oct 10 '17 at 10:47
  • 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"` – kRazzy R Dec 14 '17 at 23:31
  • Just to add to this answer: " ls > filenames.txt " creates/overwrites the content of the txt file. If you want to append more filenames/data (without overwriting previous entries) in an existing txt file simply use double >>, i.e. ls >> filenames.txt :) – Constantina Jan 30 '23 at 12:40
11

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
usta
  • 6,699
  • 3
  • 22
  • 39
  • How to ignore certain files like backup files (files having "~" as suffix in their names) ? – Vicky Dev Jun 23 '16 at 12:18
  • @VickyDev One way would be to filter `find`'s output through `grep`: `find ~/docs -type f -maxdepth 1 | grep -v '~$' > filenames.txt` – usta Jun 27 '16 at 16:42
  • @VickyDev A cleaner way is to use `find`'s `-name` with `-not`: `find ~/docs -type f -maxdepth 1 -not -name '*~' > filenames.txt` – usta Jun 27 '16 at 16:47
  • @VickyDev Please have a look at http://stackoverflow.com/questions/1341467/unix-find-for-finding-file-names-not-ending-in-specific-extensions for more on the topic – usta Jun 27 '16 at 16:49