Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only regular expression match with sed command

I'm writing to ask you help me with the following issue.

The output of "timedatectl" on my Debian system is:

Local time: Wed 2022-11-16 13:02:00 CET
           Universal time: Wed 2022-11-16 12:02:00 UTC
                 RTC time: Wed 2022-11-16 12:02:01
                Time zone: Europe/Rome (CET, +0100)
System clock synchronized: yes
              NTP service: inactive
          RTC in local TZ: no

How can I obtain only the "Europe/Rome" string, or obviously any other, using sed command?

I tried

timedatectl | sed -ne 's/^ *Time zone: \([A-z0-9_\/]*\).*$/\1/p'

but following message is returned:

sed: -e expression #1, char 40: Invalid range end

Thank you so much in advance!

like image 841
Robi Avatar asked Aug 23 '26 14:08

Robi


1 Answers

Your bracket expression contains an A-z range that does not work with your current collation rules. If you add LC_ALL=C before sed command, it won't error out, but it will still make it a bad regex since A-z ASCII char range also matches some non-letter symbols. It makes sense to replace A-z0-9 with [:alnum:].

So, you can either fix the regex and use 's/^ *Time zone: \([[:alnum:]_\/]*\).*$/\1/p' or just capture any non-whitespaces there instead:

sed -n 's/^ *Time zone: \([^ ]*\).*/\1/p'

Details:

  • -n - suppresses default line output
  • ^ *Time zone: \([^ ]*\).* - finds a line that starts with zero or more spaces, then has Time zone: string, then any zero or more chars other than space are captured into Group 1 (with \([^ ]*\)) and the rest of the line (with .*),
  • \1 - replaces the match with Group 1 value
  • p - prints the result of the successful substitution

See the online demo:

#!/bin/bash
s='Local time: Wed 2022-11-16 13:02:00 CET
           Universal time: Wed 2022-11-16 12:02:00 UTC
                 RTC time: Wed 2022-11-16 12:02:01
                Time zone: Europe/Rome (CET, +0100)
System clock synchronized: yes
              NTP service: inactive
          RTC in local TZ: no'
sed -n 's/^ *Time zone: \([^ ]*\).*$/\1/p' <<< "$s"

Output:

Europe/Rome
like image 54
Wiktor Stribiżew Avatar answered Aug 25 '26 09:08

Wiktor Stribiżew