49

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
  • 54,196
  • 25
  • 97
  • 106
alchemical
  • 13,079
  • 22
  • 82
  • 109

2 Answers2

103

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
  • 139,253
  • 125
  • 438
  • 698
  • Thankfully I googled this before writing a little bash script! – JohnAllen Feb 26 '16 at 04:38
  • 7
    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
10

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,519
  • 3
  • 21
  • 38
  • 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