Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ls, how to list files without printing the extension (the part after the dot)?

Tags:

bash

ls

Suppose I have a directory with some files:

$ ls
a.c  b.c  e.c  k.cpp  s.java

How can I display the result without the file extension(the part following the dot, including that dot)? Like this:

$ <some command>
a
b
e
k
s
like image 294
Yishu Fang Avatar asked Dec 03 '12 01:12

Yishu Fang


People also ask

How do I get filenames without an extension in Linux?

If you want to retrieve the filename without extension, then you have to provide the file extension as SUFFIX with `basename` command. Here, the extension is “. txt”.

Which option is used with ls to list all the files?

Type the ls -l command to list the contents of the directory in a table format with columns including: content permissions. number of links to the content.


4 Answers

using sed?

ls -1 | sed -e 's/\..*$//'
like image 143
Dyno Fu Avatar answered Oct 10 '22 04:10

Dyno Fu


ls | while read fname 
do
    echo ${fname%%.*}
done

Try that.

like image 37
jim mcnamara Avatar answered Oct 10 '22 05:10

jim mcnamara


ls -a | cut -d "." -f 1

man (1) cut

Very handy, the -d switch defines the delimiter and the -f which field you want.

EDIT: Include riverfall's scenario is also piece of cake as cut can start also from the end, though the logic is somewhat different. Here an example with a bunch of files with random names, some with two dots, some with a single dot and some without extension:

runlevel0@ubuntu:~/test$ ls
test.001.rpx  test.003.rpx  test.005.rpx  test.007.rpx  test.009.rpx  testxxx
test.002.rpx  test.004.rpx  test.006.rpx  test.008.rpx  test_nonum    test_xxx.rtv


runlevel0@ubuntu:~/test$ ls | cut  -d "." -f -2
test.001
test.002
test.003
test.004
test.005
test.006
test.007
test.008
test.009
test_nonum
testxxx
test_xxx.rtv

Using the minus before the field number makes it eliminate all BUT the indicated fields (1,2 in this case) and putting it behind makes it start counting from the end.

This same notation can be used for offset and characters besides of fields (see the man page)

like image 8
runlevel0 Avatar answered Oct 10 '22 03:10

runlevel0


If you already know the extension of the file, you can use basename, from the man page:

basename - strip directory and suffix from filenames

Unfortunately, it's mostly useful if you're trying to filter a single extension, in your case the command is:

basename -s .c -a $(ls *.c) && basename -s .cpp -a $(ls *.cpp) && basename -s .java -a $(ls *.java)

output:

a
b
e
k
s
like image 1
RMPR Avatar answered Oct 10 '22 05:10

RMPR