Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match pattern at the end of line/text

Tags:

bash

sed

I am very new to bash. So if this is a pretty basic question, please pardon me.

I am trying to replace file extension '.gzip' with '.gz'.

E.g.:

testfile.xml.gzip => testfile.xml.gz

Someone has written a script which does this:

GZIP=`echo ${FILE} | grep .gz`

    .
    .
    .

FILE=`echo ${FILE} | sed 's/.gz//g'`

The first line wrongly matches testfile.xml.gzip file. The grep .gz matches the text in filename which is in-between, whereas I need it to match only if it is at the end of the filename. Can anyone help me with how to correct this problem? In short, I need to know the expression which matches pattern the end of the line/text.

like image 518
Bhushan Avatar asked Mar 07 '12 20:03

Bhushan


2 Answers

Use $ to match the end of the line:

FILE=`echo ${FILE} | sed 's/.gz$//g'`

Anyway, what this command does is remove the trailing .gz extension from the filename, which isn't what you're looking for according to your question. To do that, the answer from dnsmkl is the way to go with sed.

Note that since you already have FILE in a enviroment variable you can use bash string manipulation as follows:

$ FILE=textfile.xml.gzip
$ echo ${FILE/%gzip/zip}
textfile.xml.zip
like image 107
jcollado Avatar answered Oct 04 '22 18:10

jcollado


End of string is matched by "$" in sed

For example

echo 'gzip.gzip' | sed  's|gzip$|gz|g'

Output is

gzip.gz
like image 36
dnsmkl Avatar answered Oct 04 '22 18:10

dnsmkl