Monday, October 24, 2022

[SOLVED] List files in unix in a specific format to a text file

Issue

I want to list files in a particular folder to a file list but in a particular format

for instance i have below files in a folder

/path/file1.csv /path/file2.csv /path/file3.csv

I want to create a string in a text file that lists them as below

-a file1.csv -a file2.csv -a file3.csv

assist create a script for that

ls /path/* > file_list.lst


Solution

The find utility can do this.

find /path/ -type f -printf "-a %P " > file_list.lst

This gives, for each thing that is a file in the given path (recursively), their Path relative to the starting point, formatted as in your example.

Note that:

  • Linux filenames can contain spaces and newlines; this does not deal with those.
  • The file_list.lst file will have a trailing space but no trailing newline.
  • The results will not be in a particular order.


Answered By - Wander Nauta
Answer Checked By - Cary Denson (WPSolving Admin)