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!
2
Answers
Your bracket expression contains an
A-z
range that does not work with your current collation rules. If you addLC_ALL=C
beforesed
command, it won’t error out, but it will still make it a bad regex sinceA-z
ASCII char range also matches some non-letter symbols. It makes sense to replaceA-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:Details:
-n
– suppresses default line output^ *Time zone: ([^ ]*).*
– finds a line that starts with zero or more spaces, then hasTime 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 valuep
– prints the result of the successful substitutionSee the online demo:
Output:
Using
sed