57

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.

1
  • 2
    Be careful with this, it's possible for filenames to contain all sorts of tricky characters. eg. newline Nov 6, 2010 at 6:24

2 Answers 2

115

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

5
  • Thankfully I googled this before writing a little bash script!
    – JohnAllen
    Feb 26, 2016 at 4:38
  • 8
    For absolute path printf '%s\n' "$PWD"/* >filenames.txt Jun 6, 2017 at 12:38
  • For anything beyond this trivial use, you should probably avoid ls. See mywiki.wooledge.org/ParsingLs
    – tripleee
    Oct 10, 2017 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, 2017 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 :) Jan 30 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
4
  • How to ignore certain files like backup files (files having "~" as suffix in their names) ?
    – Vicky Dev
    Jun 23, 2016 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, 2016 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, 2016 at 16:47
  • @VickyDev Please have a look at stackoverflow.com/questions/1341467/… for more on the topic
    – usta
    Jun 27, 2016 at 16:49

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.