[英]Trying to remove version number from a string using sed in OSX
I have what I hope is a simple issue which is stumping me. 我有一个希望解决的简单问题。 I need to take an installer file with a name like:
我需要一个名称如下的安装程序文件:
installer_v0.29_linux.run
installer_v10.22_linux_x64.run
installer_v1.1_osx.app
installer_v5.6_windows.exe
and zip it up into a file with the format 并将其压缩为以下格式的文件
installer_linux.zip
installer_linux_x64.zip
installer_osx.zip
installer_windows.zip
I already have a bash script running on OSX which does almost everything else I need in the build chain, and was certain I could achieve this with sed using something like: 我已经有一个在OSX上运行的bash脚本,它可以完成构建链中所需的几乎所有其他工作,并且可以通过使用sed来实现此目的,例如:
ZIP_NAME=`echo "$OUTPUT_NAME" | sed -E 's/_(?:\d*\.)?\d+//g'`
That is, replacing the regex _(?:\\d*\\.)?\\d+
with a blank - the regex should match any decimal number preceded by an underscore. 也就是说,用空格替换正则表达式
_(?:\\d*\\.)?\\d+
-正则表达式应匹配任何带下划线的十进制数。
However, I get the error RE error: repetition-operator operand invalid
when I try to run this. 但是,我收到错误
RE error: repetition-operator operand invalid
尝试运行此RE error: repetition-operator operand invalid
时, RE error: repetition-operator operand invalid
。 At this stage I am stumped - I have Googled around this and can't see what I am doing wrong. 在这个阶段,我很困惑-我已经在Google周围搜索了,看不到我在做什么错。 The regex I wrote works correctly at Regexr , but clearly some element of it is not supported by the sed implementation in OSX.
我编写的regex在Regexr上可以正常工作,但显然OSX中的sed实现不支持其中的某些元素。 Does anyone know what I am doing wrong?
有人知道我在做什么错吗?
You can try this sed
: 您可以尝试使用此
sed
:
sed 's/_v[^_]*//; s/\.[[:alnum:]]\+$/.zip/' file
installer_linux.zip
installer_linux_x64.zip
installer_osx.zip
installer_windows.zip
You don't need sed
, just some parameter expansion magic with an extended pattern. 您不需要
sed
,而只是带有扩展模式的一些参数扩展魔术。
shopt -s extglob
zip_name=${OUTPUT_NAME/_v+([^_])/}
The pattern _v+([^_])
matches a string starting with _v
and all characters up to the next _
. 模式
_v+([^_])
与以_v
开头的字符串以及直到下一个_
所有字符匹配。 The extglob
option enables the use of the +(...)
pattern to match one or more occurrences of the enclosed pattern (in this case, a non- _
character). 使用
extglob
选项可以使用+(...)
模式来匹配一个或多个出现的封闭模式(在这种情况下为非_
字符)。 The parameter expansion ${var/pattern/}
removes the first occurrence of the given pattern from the expansion of $var
. 参数扩展
${var/pattern/}
从$var
的扩展中删除给定模式的首次出现。
Try this way also 也尝试这种方式
sed 's/_[^_]\+//' FileName
OutPut: 输出:
installer_linux.run
installer_linux_x64.run
installer_osx.app
installer_windows.exe
If you want add replace zip
instead of run
use below method 如果要添加替换
zip
而不是run
使用以下方法
sed 's/\([^_]\+\).*\(_.*\).*/\1\2.zip/' Filename
Output : 输出:
installer_linux.run.zip
installer_x64.run.zip
installer_osx.app.zip
installer_windows.exe.zip
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.