33

I have a filename like a.b.c.txt, I want this string to be split as

string1=a.b.c
string2=txt

Basically I want to split filename and its extension. I used cut but it splits as a,b,c and txt. I want to cut the string on the last delimiter.

Can somebody help?

3 Answers 3

56
 #For Filename
 echo "a.b.c.txt" | rev | cut -d"." -f2-  | rev
 #For extension
 echo "a.b.c.txt" | rev | cut -d"." -f1  | rev
3
  • Beauty of code!
    – Nam G VU
    Jan 26, 2020 at 5:42
  • old school unix classic way
    – Merlin
    Jun 19, 2020 at 20:03
  • rev is really smart Mar 22, 2022 at 9:07
22

There are many tools to do this.

As you were using cut :

$ string1="$(cut -d. -f1-3 <<<'a.b.c.txt')"
$ string2="$(cut -d. -f4 <<<'a.b.c.txt')"
$ echo "$string1"
a.b.c
$ echo "$string2"
txt

I would have used parameter expansion (if the shell supports it) :

$ name='a.b.c.txt'
$ string1="${name%.*}"
$ string2="${name##*.}"
$ echo "$string1"
a.b.c
$ echo "$string2"
txt
2
  • 2
    the bash solution is elegant. Aug 8, 2017 at 13:50
  • 3
    the cut one does only work with a fixed number of periods! Aug 8, 2017 at 13:50
3
echo "a.b.c.txt" | cut -d. -f1-3

cut command will delimit . and will give you 4 factors (a, b, c, txt). Above command will print factor 1 to 3 (included).

Or:

echo "a.b.c.txt" | cut -d -f-3

Above command will print factor 1 till 3 (included).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .