creating a list of files with file absolute path in linux

Viewed 80

I have a large sum of files (~50000 files).

ls /home/abc/def/

file1.txt
file2.txt
file3.txt
.........
.........
file50000.txt

I want to create a CSV file with two columns: first column provides the filename and the second provides the absolute file path as:

output.csv

file1.txt,/home/abc/def/file1.txt
file2.txt,/home/abc/def/file2.txt
file3.txt,/home/abc/def/file3.txt
.........................
.........................
file50000.txt,/home/abc/def/file50000.txt

How to do this with bash commands. I tried with ls and find as

find /home/abc/def/ -type f -exec ls -ld {} \; | awk '{ print $5, $9 }' > output.csv

but this gives me absolute paths. How to get the output as shown in output.csv above

4 Answers

You can get both just the filename and the full path with GNU find's -printf option:

find /home/abc/def -type f -printf "%f,%p\n"

Pipe through sort if you want sorted results.

How about:

$ find /path/ | awk -F/ -v OFS=, '{print $NF,$0}'

Add proper switches to find where needed.

if u wanna fully canonicalize all existing paths, including fixing duplicate / and resolving symlinks out to their physical why not just

   find … -print0               |
or
   gls --zero                   |
or 
   mawk 8 ORS='\0' filelist.txt |

           xargs -0 -P 8 grealpath -ePq

In plain bash:

for file in /home/abc/def/*.txt; do printf '%s,%s\n' "${file##*/}" "$file"; done

or,

dir=/home/abc/def
cd "$dir" && for file in *.txt; do printf '%s,%s\n' "$file" "$dir/$file"; done
Related