Get latest filename without extension

I need to write a shell script to display the output of ls command like this

ls -ltr *txt

I get this

-rw-r----- 1 oracle dba 51912704 Dec 11 10:27 /usr/local/sam/test12112012101247AM.txt
-rw-r--r-- 1 oracle dba        7 Dec 11 11:58 /usr/local/sam/test.txt

but I just need the latest file name without extension:

test

Thanks
Sam

Your point for doing this is what?

$ ls -ltr *.txt| sed "s/\.[^\.]*$//"

(*.txt is not the same as *txt)

Using Scott's solution, you can add an awk statement to get latest file:-

ls -ltr | sed "s/\.[^\.]*$//" | awk ' { file=$NF; } END { print file; } '
1 Like

Why use -l (the 'ell' option) at all if all that's needed is the filename? In which case, tail (or head without the -r) would suffice (since $NF isn't guaranteed to give the whole filename anyway).

You are correct , I just need file name without the .txt extension Your solution worked.

I need this to create a batch job that figures out the latest *.txt file name on the server in a specific directory.

Thanks
Sam

---------- Post updated at 01:39 PM ---------- Previous update was at 01:39 PM ----------

bipinajith: Your solution works as I needed. Thanks

You don't need -l to get sorted output, that's what -t does. Leaving it off makes everything simpler. Just match the first .txt, remove the extension, print, quit.

# Only run this code for lines ending in .txt
# Delete .txt
# Print the line
# exit without printing more lines

ls -t | awk '/[.]txt$/ { sub(/[.]txt/,""); print; exit }'

what about this code? (...or did I miss something :p)

~/unix.com$ ls -t *.txt | awk 'NR==1&&gsub(/.txt$/,"")'

It has a few limitations.

1) Shell globbing has a maximum number of files, *.txt may break if there are too many.
2) You forgot to remove the file extension.
3) Sneaking an edit under me doesn't mean you didn't forget to remove the file extension :smiley: