如何在行/文本末尾匹配模式 [英] How to match pattern at the end of line/text

查看:50
本文介绍了如何在行/文本末尾匹配模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对bash非常陌生.因此,如果这是一个非常基本的问题,请原谅我.

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

我正在尝试将文件扩展名' .gzip '替换为' .gz '.

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

例如:

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'`

第一行错误地匹配了 testfile.xml.gzip 文件. grep .gz 匹配中间的文件名中的文本,而我仅在文件名末尾才需要匹配.谁能帮我解决这个问题?简而言之,我需要知道匹配模式的行/文本末尾的表达式.

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.

推荐答案

使用 $ 匹配行尾:

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

无论如何,此命令的作用是从文件名中删除尾随的 .gz 扩展名,这不是您根据问题所要查找的扩展名.为此,dnsmkl的答案就是使用 sed 的方式.

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.

请注意,由于环境变量中已有 FILE ,因此可以使用bash 字符串操作如下:

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

这篇关于如何在行/文本末尾匹配模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆