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!
CodePudding user response:
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 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 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
CodePudding user response:
Using sed
$ sed -En '/Time zone/s~[^/]* ([^ ]*).*~\1~p' input_file
Europe/Rome
