Script to get file extensions

I need to get all types of file extensions in a folder. For example, if the ls directory gives the following:

a.t  
b.t.pg  
c.bin  
d.bin  
e.old  
f.txt  
g.txt  

I have to get this by running a script

.t  
.t.pg  
.bin  
.old  
.txt  

I have a bash shell.

Thank you so much!

+3
source share
3 answers

try the following:

ls -1 | sed 's/^[^.]*\(\..*\)$/\1/' | sort -u
  • ls lists files in your folder, one file per line
  • sed extensions extensions for magic
  • sort -u sorts extensions and removes duplicates

sed magic reads like:

  • s/ / /: replaces everything that is between the first and second / what is between the second and third /
  • ^: start of line match
  • [^.]: match any character that is not a period
  • *: match it as often as possible
  • \(and \): remember everything that matches between these two parentheses
  • \.: match point
  • .:
  • *:
  • $:
  • \1: ,
+3

. BashFAQ ParsingLS , .

(, , ):

shopt -s nullglob
for f in *.*; do
  printf '%s\n' ".${f#*.}"
done | sort -u

:

  • : ls . . .
  • : ( , sort -u, , Bash 4 )

:

  • : . ( ), . sort. Bash 4 .
+7

People really overcomplicate this - a particularly regular expression:

ls | grep -o "\..*" | uniq

ls- get all files
grep -o "\..*"- -oshows only a match; "\..*"matches the first "." and everything after it
uniq- do not print duplicates, but keep the same order

you can also sort if you want, but sorting doesn't match the example

Here's what happens at startup:

> ls -1
a.t
a.t.pg
c.bin
d.bin
e.old
f.txt
g.txt

> ls | grep -o "\..*" | uniq
.t
.t.pg
.bin
.old
.txt
0
source

All Articles