stefandz
stefandz

Reputation: 60

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:

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.

However, I get the error RE error: repetition-operator operand invalid when I try to run this. At this stage I am stumped - I have Googled around this and can't see what I am doing wrong. The regex I wrote works correctly at Regexr, but clearly some element of it is not supported by the sed implementation in OSX. Does anyone know what I am doing wrong?

Upvotes: 1

Views: 1590

Answers (3)

chepner
chepner

Reputation: 530843

You don't need sed, just some parameter expansion magic with an extended pattern.

shopt -s extglob
zip_name=${OUTPUT_NAME/_v+([^_])/}

The pattern _v+([^_]) matches a string starting with _v and all characters up to the next _. 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). The parameter expansion ${var/pattern/} removes the first occurrence of the given pattern from the expansion of $var.

Upvotes: 1

anubhava
anubhava

Reputation: 784878

You can try this sed:

sed 's/_v[^_]*//; s/\.[[:alnum:]]\+$/.zip/' file
installer_linux.zip
installer_linux_x64.zip
installer_osx.zip
installer_windows.zip

Upvotes: 1

Kalanidhi
Kalanidhi

Reputation: 5092

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

sed 's/\([^_]\+\).*\(_.*\).*/\1\2.zip/' Filename

Output :

installer_linux.run.zip
installer_x64.run.zip
installer_osx.app.zip
installer_windows.exe.zip

Upvotes: 0

Related Questions