Thursday, May 2, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 6596  / 2 Years ago, sun, january 16, 2022, 12:34:24

I have lines form a command output as given below.



service:clus1-svr          clus1-node2                      started    [Z]
service:clus1-svr clus1-node2 started


I want to add string before and after the line which indicate [Z] only. So the result may come as:



<font>service:clus1-svr          clus1-node2                      started    [Z]</font>


Can anyone please help me to do this. Your help greatly appreciated.



i tried below, but that changes all the line from the output



sed -i "s/.*/<font color="red">&</font>/"

More From » text-processing

 Answers
5

You were pretty close with your attempt; all you needed to do was to narrow down the execution of the substitution only to lines containing [Z] at the end:



sed -i '/[Z]$/ s/.*/<font>&</font>/' infile


However, here's another awk solution:



awk '$4=="[Z]" {printf("%s%s%s
", "<font>", $0, "</font>"); next} {print}' infile



  • $4=="[Z]": pattern; if the 4th field of the currently processed record is [Z], executes the following action; otherwise, it skips to the next pattern / action;

  • printf("%s%s%s
    ", "<font>", $0, "</font>")
    : prints <font>, the currently processed record and </font> as strings followed by a newline;

  • next: skips to the next record;

  • print: prints the currently processed record followed by a newline;



Sample output:



user@debian ~ % cat infile
service:clus1-svr clus1-node2 started [Z]
service:clus1-svr clus1-node2 started
user@debian ~ % awk '$4=="[Z]" {printf("%s%s%s
", "<font>", $0, "</font>"); next} {print}' infile
<font>service:clus1-svr clus1-node2 started [Z]</font>
service:clus1-svr clus1-node2 started

[#18507] Sunday, January 16, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amacal

Total Points: 457
Total Questions: 102
Total Answers: 116

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;