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
Related videos on Youtube
Author by
alchemical
Thus have I heard: Premature optimization is the root of all evil.
Updated on November 06, 2020Comments
-
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 over 13 yearsBe careful with this, it's possible for filenames to contain all sorts of tricky characters. eg. newline
-
-
JohnAllen about 8 yearsThankfully I googled this before writing a little bash script!
-
Vicky Dev almost 8 yearsHow to ignore certain files like backup files (files having "~" as suffix in their names) ?
-
usta almost 8 years@VickyDev One way would be to filter
find
's output throughgrep
:find ~/docs -type f -maxdepth 1 | grep -v '~$' > filenames.txt
-
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 almost 8 years@VickyDev Please have a look at stackoverflow.com/questions/1341467/… for more on the topic
-
Prince Patel almost 7 yearsFor absolute path
printf '%s\n' "$PWD"/* >filenames.txt
-
tripleee over 6 yearsFor anything beyond this trivial use, you should probably avoid
ls
. See mywiki.wooledge.org/ParsingLs -
kRazzy R over 6 yearsWhat 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"