How to match pattern at end of line / text

I am very new to bash. Therefore, if this is a fairly simple question, please forgive me.

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

eg:.

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

Someone wrote a script that does this:

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

The first line mistakenly corresponds to the testfile.xml.gzip file. grep .gz matches the text in the file name that is between them, whereas I need it to match only if it is at the end of the file name. Can someone help me in solving this problem? In short, I need to know an expression that matches the pattern at the end of a line / text.

+6
source share
4 answers

Use $ to match the end of the line:

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

Anyway, what this command does is remove the final .gz extension from the file name, which is not what you are looking for according to your question. For this, the answer from dnsmkl is the sed path.

Note that since you already have FILE in the environment variable, you can use bash string manipulation as follows:

 $ FILE=textfile.xml.gzip $ echo ${FILE/%gzip/zip} textfile.xml.zip 
+13
source

The end of the string matches "$" in sed

for instance

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

Exit

 gzip.gz 
+6
source

should do a while.gzip directory

(ls * .gzip | when reading a line, do mv "$ line" "$ (basename" $ ​​line ".gzip) .gz"; done)

0
source

This may work for you:

 rename gzip gz *gzip 
0
source

Source: https://habr.com/ru/post/910202/


All Articles