28

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?

Thomas Dickey
  • 75,040
  • 9
  • 171
  • 268
chhaya vishwakarma
  • 693
  • 6
  • 12
  • 18

3 Answers3

52
 #For Filename
 echo "a.b.c.txt" | rev | cut -d"." -f2-  | rev
 #For extension
 echo "a.b.c.txt" | rev | cut -d"." -f1  | rev
jijinp
  • 1,361
  • 9
  • 10
18

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
heemayl
  • 54,820
  • 8
  • 124
  • 141
2
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).

Yurij Goncharuk
  • 4,177
  • 2
  • 19
  • 36