0

I wanted to list down all the filenames within a folderA and another folderB inside folderA and saved it to a text file. The code I used is:

ls -1 /home/CSV_XXX/* | grep ^'/home/CSV_XXX' >/home/Lists.txt

Suppose I've a folder named CSV_XXX in the directory '/home/CSV_XXX' & inside it contains:

20161010
BDL_EXISTING_CARDS2_20161228.CSV
BDL_EXISTING_COLLATERAL_20161228.CSV
BDL_EXISTING_CUST_ADDRESS_20161228.CSV
.
.
.

'20161010' is a folder inside CSV_XXX with the directory '/home/CSV_XXX/20161010' & contains:

BDL_EXISTING_CARDS2_20161010.CSV
BDL_EXISTING_COLLATERAL_20161010.CSV
BDL_EXISTING_CUST_ADDRESS_20161010.CSV
.
.
.

However, I couldn't get what I want.

During my first attempt, I got:

/home/CSV_XXX/BDL_EXISTING_CARDS2_20161010.CSV
/home/CSV_XXX/BDL_EXISTING_COLLATERAL_20161010.CSV
/home/CSV_XXX/BDL_EXISTING_CUST_ADDRESS_20161010.CSV
.
.
.
/home/CSV_XXX/20161010:

without the list of what's in the folder 20161010

Also, how can I remove the directory '/home/CSV_XXX/' if I change my mind to remove it in my list?

just the lists (including 20161010):

BDL_EXISTING_CARDS2_20161228.CSV
BDL_EXISTING_COLLATERAL_20161228.CSV
BDL_EXISTING_CUST_ADDRESS_20161228.CSV
.
.
.
1

You may be better using the find command

eg

find /home/CSV_XXX -type f -print

will list all the files in all the directories recursively under the CSV_XXX directory.

If you only want files matching a pattern then you can do something like

find /home/CSV_XXX -type f -name '*.csv' -print

and that will only print filenames ending in .csv

If you want to include directories in the list then just skip the -type f part.

To remove the directory prefix;

( cd /home/CSV_XXX ; find * -type f -name '*.csv' -print )

  • Thanks alot ~~~ The script are working fine :) except that find /home/CSV_XXX -type f -name '*.csv' -print don't seem to be working. I got the error ksh: /CSV_XXX/LISTS.txt: 0403-005 Cannot create the specified file. – Juliet.Y Feb 17 '17 at 6:13
0

By default, ls is not recursive. You would need to add the -R flag for it to descend into subdirectories. You may find that find is a better command to use though as ls doesn't give the full path name whereas find does by default.

To remove a file from list output, use grep -v.

The man pages for ls, find and grep can give you further detail.

  • I actually tried ls -r instead, it do work... but somehow when I grep it into the text file it doesn't work. – Juliet.Y Feb 17 '17 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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