cut string on last delimiter

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?

 #For Filename
 echo "a.b.c.txt" | rev | cut -d"." -f2-  | rev
 #For extension
 echo "a.b.c.txt" | rev | cut -d"." -f1  | rev
Answered By: jijinp

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
Answered By: heemayl
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).

Answered By: Rohit Chaudhari
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.