Getting filenames from a directory in single line

Hi All,

I have a requirement where I need to get the all file names present in a particular directory in to a single separated by space,

I have files in /home/RAAM/work directory as
test1.xls
test2.xls
test3.xls

I need to get all filenames from that directory in single line like
test1.xls test2.xls test3.xls

I am using the following commend
ls -ltr /home/RAAM/work/*.xls | awk '{print $9}' |cut -d'/' -f5

It is giving the output like
test1.xls
test2.xls
test3.xls

that means in separate lines it is giving. How can I remove the new line character from cut output without using any temporary variables?

I used the following to remove /n
ls -ltr /home/rameshch/bhanu/*.xls | awk '{print $9}' |cut -d'/' -f5 | tr -d'\n'

it is erroring out. Can any one please help?

In awk, the print command will always add a newline, use printf() instead.

ls | awk ' { printf( "%s ", $NF ) } END { printf( "\n" ); }'

Also, you can 'cut' away the path with a simple sub() function call in the awk rather than adding the extra overhead required by using cut.

sub( ".*/", "", $NF );

Hi Agama,

Thank you very much, that worked.

I need one more small clue, I got the output like this
/home/RAAM/work/test1.xls /home/RAAM/work/test2.xls

I need to get only filenames with out directory structure, can you please help.

Thank you very much for quick response.

--Thanks,
--Raam.

Or just use the shell wildcard expansion

FILES=$( cd /home/RAAM/work/ ; echo *.xls )

or simply the following if you dont need files in a variable

( cd /home/RAAM/work/ ; echo *.xls )
1 Like

Updated from Agama's code, that you need understand the FS (field separator) in awk.

awk -F \/ '{ printf( "%s ", $NF ) } END { printf( "\n" ); }'

but Chubler_XL's code is more simple.

Thank you all,

It is working as it is required.

Appreciate your help.

--Thanks
--Raam

For what it's worth, I think the error in this attempt was simply that tr -d'\n' needs a space after the d.

(my ls -ltr only gives 8 columns so im using awk '{print $8}' )

# ls -ltr *.xls | awk '{print $8}' |cut -d'/' -f5 | tr -d'\n'
tr: invalid option -- '\'
Try `tr --help' for more information.

# ls -ltr *.xls | awk '{print $8}' |cut -d'/' -f5 | tr -d '\n'
test3.xlstest2.xlstest1.xls#

With the space, it doesn't error, but it shows that you'd need to use tr '\n' ' ' to replace newlines with a space instead of just deleting newlines. Of course "echo *.xls" is much more elegant, but I think your only trouble was that one little space.