Is there a way to format the following output so that only lines 1 and 4 print out? It would be best if the first line and fourth line could come out on the same line like this:

sw pool test(no bracket)status up

Example command and output:

  • command:

    show server pool
  • output:

    sw pool test {
    members 1
    status up

Desired output formatting (note that the curly bracket that was at the end of line 1 should be removed):

sw pool test status up

How can I get this output, preferably using awk?


Using awk

This prints the first line without { and the fourth line:

$ show server pool | awk 'NR==1{sub(/{/, ""); printf "%s",$0} NR==4'
sw pool test status up

How it works

  • NR==1{sub(/{/, ""); printf "%s",$0}

    The condition NR==1 selects the first line. For this line, the { is removed with the sub command and then the line is printed using printf (without a trailing newline).

  • NR==4

    The condition NR==4 selects the fourth line. Since no action is specified for this condition, awk does the default action which is. just as we want, to print the line.

Using sed

The same thing is possible with sed:

$ show server pool | sed 'h;N;N;x;N; s/{\n//'
sw pool test status up

How it works

  • h

    This saves the first line in the hold space.

  • N;N

    This reads in lines 2 and 3.

  • x

    This swaps the hold and pattern space. This puts line 1 back in the pattern space.

  • N

    This reads in the next line, line 4, into the pattern space, appending it to line 1.

  • s/{\n//

    This removes the brace and newline from the end of line 1 so that line 1 and line 4 are now merged with brace removed. This is what is printed.

  • That's great! I just tried and ran into a few unexpected snags but your tutorial was perfect. I will post one more question to maybe handle the snags I ran into. Thank you. – jogle900 Mar 31 '15 at 3:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.