bash 如何匹配行/文本末尾的模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9608483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:45:06  来源:igfitidea点击:

How to match pattern at the end of line/text

bashsed

提问by Bhushan

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

我对 bash 很陌生。所以如果这是一个非常基本的问题,请原谅我。

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

我正在尝试.gzip用“ .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.gzipfile. The grep .gzmatches 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.

第一行错误地匹配testfile.xml.gzip文件。将grep .gz在文件名的文本是在两者之间,而我需要的,如果它是在文件名末尾它只匹配匹配。谁能帮我解决这个问题?简而言之,我需要知道匹配行/文本末尾模式的表达式。

回答by jcollado

Use $to match the end of the line:

使用$该行的末尾匹配:

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

Anyway, what this command does is remove the trailing .gzextension 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.

无论如何,此命令的作用是.gz从文件名中删除尾随扩展名,根据您的问题,这不是您要查找的内容。要做到这一点,来自 dnsmkl 的答案是使用sed.

Note that since you already have FILEin a enviroment variable you can use bash string manipulationas follows:

请注意,由于您已经FILE在环境变量中,您可以按如下方式使用 bash字符串操作

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

回答by dnsmkl

End of string is matched by "$" in sed

字符串的结尾在 sed 中与“$”匹配

For example

例如

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

Output is

输出是

gzip.gz

回答by str8

should do a while directory of .gzip files

应该做一个 .gzip 文件的目录

(ls *.gzip | while read line; do mv "$line" "$(basename "$line" .gzip).gz"; done)

(ls *.gzip | while read line; do mv "$line" "$(basename "$line" .gzip).gz"; done)

回答by glenn Hymanman

Thismay work for you:

可能对您有用:

rename gzip gz *gzip