简体   繁体   中英

How do I delete matching text with sed but keep the rest of the line?

I have a format string that is generally of the format:

PRODUCT_NAME-VERSION-OS(-INSTALLER)?.SUFFIX

I want to delete just the VERSION part of it. VERSION is defined as something matching: [0-9]+\\.[0-9]+\\.[0-9]+ . Therefore I want to do something like: echo NAME | sed -i "\\-/[0-9]+\\.[0-9]+\\.[0-9]+/d echo NAME | sed -i "\\-/[0-9]+\\.[0-9]+\\.[0-9]+/d so that I get PRODUCT_NAME-OS(-INSTALLER)?.SUFFIX .

How do I do that?

Eg

  • Dropbox-1.0.0-win32-setup.exe -> Dropbox-win32-setup.exe
  • gdrive-2.32.1-linux.deb -> gdrive-linux.deb
  • azure-92.0.3-mac-osx -> azure-mac-osx

sed deletion operates over the matched line. So, in your exammple, you'd be deleting the entire line. You should head for substitutions instead. Take a look at the examples below:

$ sed -E 's/(.*)-[0-9]+\.[0-9]+\.[0-9]+(.*)/\1\2/'
    <<< "Dropbox-1.0.0-win32-setup.exe"
Dropbox-win32-setup.exe

$ sed -E 's/(.*)-[0-9]+\.[0-9]+\.[0-9]+(.*)/\1\2/'
    <<< "gdrive-2.32.1-linux.deb"
gdrive-linux.deb

$ sed -E 's/(.*)-[0-9]+\.[0-9]+\.[0-9]+(.*)/\1\2/'
    <<< "azure-92.0.3-mac-osx"
azure-mac-osx

Just remove all from first - to second -

cat file
PRODUCT_NAME-VERSION-OS-INSTALLER.SUFFIX
PRODUCT_NAME-VERSION-OS.SUFFIX
Dropbox-1.0.0-win32-setup.exe
gdrive-2.32.1-linux.deb
azure-92.0.3-mac-osx

sed 's/-.*-/-/' file
PRODUCT_NAME-INSTALLER.SUFFIX
PRODUCT_NAME-OS.SUFFIX
Dropbox-setup.exe
gdrive-linux.deb
azure-osx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM