RSH
RSH

Reputation: 395

BASH split a string and return all of the text before that word

I have a situation where I have a string that includes the information that I need to get, and then a warning which I want to get rid of:

Time Sync Status:       Local time: Mon 2020-04-06 19:25:43 EDT
  Universal time: Mon 2020-04-06 23:25:43 UTC
        RTC time: n/a
       Time zone: America/New_York (EDT, -0400)
 Network time on: no
NTP synchronized: no
 RTC in local TZ: yes


         Warning: This mode can not be fully supported. It will create various problems
         with time zone changes and daylight saving time adjustments. The RTC
         time is never updated, it relies on external facilities to maintain it.
         If at all possible, use RTC in UTC by calling
         'timedatectl set-local-rtc 0'.

So I am trying to split the string on "Warning" and get the text before that...but I have tried many things and nothing is working for me:

echo Time Sync Status: "$(timedatectl status | awk -F 'Warning' '{print $1}')"

How can I achieve this?

TIA Ron

Upvotes: 0

Views: 78

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133428

Could you please try following.

awk '/Warning/{exit} 1' Input_file

OR

echo "$string" | awk '/Warning/{exit} 1'

Explanation: Simply looking for word Warning and once it occurs simply exit from program then. Before that it will print every line.



2nd solution: In case you want all the lines before word Warning and want to leave empty lines too then try following.

awk '/Warning/{exit};NF' Input_file

OR

echo "$string" | awk '/Warning/{exit};NF'


3rd solution: In case OP wants to do in his/her style only then try(tested and written in GNU awk). we need to set record separator to make FS work here.

awk -v RS="" -v FS="Warning" '{print $1}'  Input_file

OR

echo "$string" | awk -v RS="" -v FS="Warning" '{print $1}'

Upvotes: 3

Related Questions