Replace/remove 2 characters with space in a sed one-liner

Viewed 65

Merciful overlords of sed, here's my raw output:

reboot   system boot  3.10.0-327.28.3. Sun Jan 10 02:16 - 06:52  (04:36)
reboot   system boot  3.10.0-327.28.3. Wed Jan  6 02:00 - 06:52 (4+04:52)
reboot   system boot  3.10.0-327.28.3. Sun Jan  3 00:39 - 06:52 (7+06:13)
reboot   system boot  3.10.0-327.28.3. Sat Jan  2 02:40 - 06:52 (8+04:12)
reboot   system boot  3.10.0-327.28.3. Sat Jan  2 02:39 - 06:52 (8+04:13)
reboot   system boot  3.10.0-327.28.3. Wed Dec 30 06:56 - 06:52 (10+23:56)
reboot   system boot  3.10.0-327.28.3. Wed Dec 30 02:43 - 03:17  (00:34)
reboot   system boot  3.10.0-327.28.3. Wed Dec 30 00:51 - 03:17  (02:26)
reboot   system boot  3.10.0-327.28.3. Tue Dec 29 07:14 - 03:17  (20:02)
reboot   system boot  3.10.0-327.28.3. Tue Dec 29 05:30 - 07:14  (01:44)
reboot   system boot  3.10.0-327.28.3. Tue Dec 29 05:18 - 07:14  (01:55)

My desire is to remove the parentheses in the last column with a sed one-liner, instead of using this unelegant and rookie-like snippet that is almost egregiously obvious to use:

[root@OEL7 ~]# last reboot | sed -e 's/(//g' | sed -e 's/)//g'
reboot   system boot  3.10.0-327.28.3. Sun Jan 10 02:16 - 07:12  04:55
reboot   system boot  3.10.0-327.28.3. Wed Jan  6 02:00 - 07:12 4+05:11
reboot   system boot  3.10.0-327.28.3. Sun Jan  3 00:39 - 07:12 7+06:32
reboot   system boot  3.10.0-327.28.3. Sat Jan  2 02:40 - 07:12 8+04:31
reboot   system boot  3.10.0-327.28.3. Sat Jan  2 02:39 - 07:12 8+04:32
reboot   system boot  3.10.0-327.28.3. Wed Dec 30 06:56 - 07:12 **11+00:15**
reboot   system boot  3.10.0-327.28.3. Wed Dec 30 02:43 - 03:17  00:34
reboot   system boot  3.10.0-327.28.3. Wed Dec 30 00:51 - 03:17  02:26
reboot   system boot  3.10.0-327.28.3. Tue Dec 29 07:14 - 03:17  20:02
reboot   system boot  3.10.0-327.28.3. Tue Dec 29 05:30 - 07:14  01:44
reboot   system boot  3.10.0-327.28.3. Tue Dec 29 05:18 - 07:14  01:55

I believe I've performed my due diligence before posting (including sifting through some of the suggested posts before publicizing this one) but the examples I've found do not meet my criteria:

  1. mandatory use of sed
  2. achieve the result in the shortest possible manner, without piping, etc.

Should any of you however be privy of a solution on SO that I may have missed I'd be eternally grateful for any URLs, pointers, etc.

2 Answers

IIUC, you only need:

last reboot | sed 's,[()],,g'

You could use a capture group to match all between the parenthesis followed by $ to assert the end of the string. Testing this on a mac, apparently there can be spaces at the end.

In the replacement use group 1.

sed -E 's/\(([^()]+)\)[[:space:]]*$/\1/'

Regex demo | Sed demo

Without using -E

sed 's/(\([^()]*\))[[:space:]]*$/\1/'

See another sed demo

Related