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
How to match pattern at the end of line/text
提问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.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.
第一行错误地匹配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 .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
.
无论如何,此命令的作用是.gz
从文件名中删除尾随扩展名,根据您的问题,这不是您要查找的内容。要做到这一点,来自 dnsmkl 的答案是使用sed
.
Note that since you already have FILE
in 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)