简体   繁体   English

如何删除带有sed的匹配文本,但保留其余部分?

[英]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部分。 VERSION is defined as something matching: [0-9]+\\.[0-9]+\\.[0-9]+ . VERSION定义为匹配的内容: [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 echo NAME | sed -i "\\-/[0-9]+\\.[0-9]+\\.[0-9]+/d so that I get PRODUCT_NAME-OS(-INSTALLER)?.SUFFIX . echo NAME | sed -i "\\-/[0-9]+\\.[0-9]+\\.[0-9]+/d以便获得PRODUCT_NAME-OS(-INSTALLER)?.SUFFIX

How do I do that? 我怎么做?

Eg 例如

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

sed deletion operates over the matched line. sed删除在匹配的行上进行。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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