Home > database >  List files in unix in a specific format to a text file
List files in unix in a specific format to a text file

Time:08-04

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

CodePudding user response:

You can just printf them.

printf "-a %s " /path/*

If you plan to be using it with a command, you may want to read https://mywiki.wooledge.org/BashFAQ/050 and interest yourself with %q printf format specifier.

CodePudding user response:

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.
  • Related