Linux: how to replace text between strings
One of the most common operations i have to do is to replace text between strings with another string or just delete the string, to do this…
One of the most common operations i have to do is to replace text between strings with another string or just delete the string, to do this the simplest solution i found is to use sed.
In this example i run a tool which produces the following output, what i want is to remove everything between = and ( when exists./get_db2_status.sh host database
HADR_CONNECT_STATUS = CONNECTED
HADR_CONNECT_STATUS_TIME = 06/02/2022 14:08:49.786063 (1654168129)
HADR_LOG_GAP(bytes) = 0
PRIMARY_LOG_TIME = 06/02/2022 15:38:45.000000 (1654173525)
STANDBY_LOG_TIME = 06/02/2022 15:38:45.000000 (1654173525)
STANDBY_REPLAY_LOG_TIME = 06/02/2022 15:38:45.000000 (1654173525)
STANDBY_ERROR_TIME = 06/02/2022 08:56:24.000000 (1654149384)
To achieve this i piped the output to the following sed expression./get_hard_status.sh host database | sed 's/ =.*(/ = /'
HADR_CONNECT_STATUS = CONNECTED
HADR_CONNECT_STATUS_TIME = 1654168129)
HADR_LOG_GAP(bytes) = 0
PRIMARY_LOG_TIME 1654173525)
STANDBY_LOG_TIME 1654173525)
STANDBY_REPLAY_LOG_TIME 1654173525)
STANDBY_ERROR_TIME 1654149384)
How it works
s/ =.*(/ : Capture everything starting with a space continues with an equal sign and ends with the ( character.
/ = / : Replace the everything captured with a space an equal sign and another space
Just a last tweak
if you noticed, some lines end with ( , to remove ( if exists we can then further pipe the result to another statement's/)$//' <-- this will remove every character in a line ends with '('
Example./get_hard_status.sh host database | sed 's/ =.*(/ = /' | sed 's/)$//'
HADR_CONNECT_STATUS = CONNECTED
HADR_CONNECT_STATUS_TIME = 1654168129
HADR_LOG_GAP(bytes) = 0
PRIMARY_LOG_TIME = 1654173525
STANDBY_LOG_TIME = 1654173525
STANDBY_REPLAY_LOG_TIME = 1654173525
STANDBY_ERROR_TIME = 1654149384
I hope you found this short article useful :)