Search code examples
linuxbashls

Using LS for a specific path & file type without returing full file path?


I am writing a bash script and would like to use LS giving it a path/*.tar and have it return just file names instead of full path and file name to pass the file names through read into an array, below is what happens in terminal:

If i just use LS with a directory it returns:

admin@linuxbox:~$ ls  /home/admin/Backup/
0_BuIndex.txt.backup  Backup1376238064.tar  Backup1376239611.tar  Backup1376241919.tar
Backup1376167035.tar  Backup1376238960.tar  Backup1376240158.tar  Backup1376243097.tar
Backup1376168581.tar  Backup1376239110.tar  Backup1376241421.tar
Backup1376237070.tar  Backup1376239350.tar  Backup1376241489.tar
Backup1376237928.tar  Backup1376239479.tar  Backup1376241608.tar

Giving path & file type it returns:

admin@linuxbox:~$ ls  /home/admin/Backup/*.tar
/home/admin/Backup/Backup1376167035.tar  /home/admin/Backup/Backup1376239479.tar
/home/admin/Backup/Backup1376168581.tar  /home/admin/Backup/Backup1376239611.tar
/home/admin/Backup/Backup1376237070.tar  /home/admin/Backup/Backup1376240158.tar
/home/admin/Backup/Backup1376237928.tar  /home/admin/Backup/Backup1376241421.tar
/home/admin/Backup/Backup1376238064.tar  /home/admin/Backup/Backup1376241489.tar
/home/admin/Backup/Backup1376238960.tar  /home/admin/Backup/Backup1376241608.tar
/home/admin/Backup/Backup1376239110.tar  /home/admin/Backup/Backup1376241919.tar
/home/admin/Backup/Backup1376239350.tar  /home/admin/Backup/Backup1376243097.tar

I would like to use a command like the second but have it only return the file names without the path, my work around right now is to use

read -r -a TarArray <<< `ls -1 /home/admin/Backup | grep "tar"`

but I am hoping to find a solution that doesn't require me to pipe through grep.

Any ideas? Thanks all!


Solution

  • You could potentially use find for this :

    find /home/admin/Backup -name \*.tar -printf '%f\n'
    

    From the man page :

    -printf format
        True;  print  format  on  the standard output,
        interpreting `\' escapes and `%' directives.
        ...
        %f     File's name with any leading directories
               removed (only the last element).