16

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?

30
 #For Filename
 echo "a.b.c.txt" | rev | cut -d"." -f2-  | rev
 #For extension
 echo "a.b.c.txt" | rev | cut -d"." -f1  | rev
| improve this answer | |
  • Beauty of code! – Nam G VU Jan 26 at 5:42
  • old school unix classic way – Merlin Jun 19 at 20:03
15

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
| improve this answer | |
  • 1
    the bash solution is elegant. – törzsmókus Aug 8 '17 at 13:50
  • the cut one does only work with a fixed number of periods! – törzsmókus Aug 8 '17 at 13:50
0
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).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.