-1

New to Linux commands.. What syntax would I use to find and replace a string with each line starting with "Data Centre:" Address information that is different on every line" but ends with the word Site: and I need to keep the site details that follow..

Example:

Input.txt
Data Centre: 23 Mulberry lane, Washington Site: 9067 Green

Expected Output
Site: 9067 Green

I've found gsub examples, but gsub is not available on my OS.

Any help appreciated.

Mac

pa4080
  • 29,831
majtx
  • 3
  • 1
    " gsub is not available on my OS". If you're using non-Ubuntu OS, you should be asking on unix.stackexchange.com. Questions posted here are Ubuntu specific and specific to tools used on Ubuntu – Sergiy Kolodyazhnyy Sep 13 '18 at 07:30
  • I remember correctly, I was installed gawk (sudo apt install gawk) on my Ubuntu 16.04 to have gsub available. – pa4080 Sep 13 '18 at 07:42
  • I have 16.04 and gsub works out of the box. – pLumo Sep 13 '18 at 08:07

2 Answers2

3

If you use semicolon as field separator, what you want will be in the last field

awk -F ':'  '/Site:/ { print "Site: ", $NF }'
Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
  • Thanks Sergiy, very fast, I have a few other comments after the Status of green, I understand the NF is number of fields, is there away of also displaying these e.g in my simple example above there often Warnings if Amber which might call out a fault. Effectively I need to print anything after the Site: Thanks so much. – majtx Sep 13 '18 at 07:42
  • 1
    It works, but two extra white spaces are added after Site:. Here is with printf: awk -F ':' '/Site:/ { printf "%s\n","Site:"$NF }' Input.txt – pa4080 Sep 13 '18 at 07:49
  • @majtx OK, I can edit an answer, but you need to provide the full structure of the file. How do warnings look like ? Do items after site have constant number of strings, like , or can it be ? – Sergiy Kolodyazhnyy Sep 13 '18 at 08:09
  • @pa4080 The two whitespaces are added in the "Site: " part itself. But yes, printf can do just fine there. – Sergiy Kolodyazhnyy Sep 13 '18 at 08:10
  • @majtx Also do ls -l /etc/alternatives/awk so we at least know what type of awk you have on your system. – Sergiy Kolodyazhnyy Sep 13 '18 at 08:12
  • @majtx, if [this] answer was helpful to you, then please consider marking it as the accepted answer (by click on the grey tick ✓ left to it) so others may more easily find it in the future. This is also a polite way to thank the person answering your question for helping you out. – pa4080 Sep 13 '18 at 17:07
3

Here is a sed solution that uses extended regular expressions -r and capture groups ()->\1:

sed -r 's/^Data Centre:.*(Site: .*)$/\1/' Input.txt

If you want to suppress the output of any other lines that could appear in the file:

sed -n -r 's/^Data Centre:.*(Site: .*)$/\1/p' Input.txt

Add the option -i.bak to do the changes and backup file simultaneously, ot redirect the output to new file.

pa4080
  • 29,831