Search code examples
linuxsedtext-parsingin-place

Remove from file a string and another string and everything after it


Say I have a file teams with contents as follows:

[Desktop Entry]
Version=1.0
Type=Application
Name=Microsoft Teams - Preview
Comment=Microsoft Teams for Linux is your chat-centered workspace in Office 365.
Exec=teams %U
Icon=teams
Terminal=false
StartupNotify=true
StartupWMClass=Microsoft Teams - Preview
Categories=Network;
MimeType=x-scheme-handler/msteams;
X-KDE-Protocols=teams
Actions=QuitTeams;
X-GNOME-UsesNotifications=true;

[Desktop Action QuitTeams]
Name=Quit Teams

I'd like to remove a line Actions=QuitTeams;. This seems easy:

sed -i '/Actions=QuitTeams;/d' teams

Also, I'd like to remove a line [Desktop Action QuitTeams] and everything that comes after it (there could be new lines). This also seems easy:

sed -i '/[Desktop Action QuitTeams]]/,$d' teams

My question is: how do I do the two steps in one sed execution, i.e. combine all the regexes into one? Sed is preferred but other tools are welcomed, too.


Solution

  • You can try using sed's -e option (see 3.8 Multiple commands syntax):

    $ sed -i -e '/Actions=QuitTeams;/d' -e '/[Desktop Action QuitTeams]]/,$d' teams
    $ cat teams
    [Desktop Entry]
    Version=1.0
    Type=Application
    Name=Microsoft Teams - Preview
    Comment=Microsoft Teams for Linux is your chat-centered workspace in Office 365.
    Exec=teams %U
    Icon=teams
    Terminal=false
    StartupNotify=true
    StartupWMClass=Microsoft Teams - Preview
    Categories=Network;
    MimeType=x-scheme-handler/msteams;
    X-KDE-Protocols=teams
    X-GNOME-UsesNotifications=true;