alpha
alpha

Reputation: 103

Formatting text output in Bash

I have some output from a pdsh I want to format it to load into a DB. I need it in 3 columns and essentially want the Module ID and the message on one line. Bellow is the output i have:

10.125.45.58,scope, Module ID     = server-1
10.125.45.58,scope, Message       = Correctable memory error
10.125.45.58,scope, Module ID     = server-2
10.125.45.58,scope, Message       = Correctable memory error 

This is the output i need:

10.125.45.58,scope,server-1 Correctable memory error
10.125.45.58,scope,server-2 Correctable memory error

I have been awking and seding...i cant work it out any ideas?

Here is what I've done so far

cat myfile.txt | sed -e "s/:/\,scope\,/g" | grep -E '(Module ID|Message)'

Thank you.

Upvotes: 0

Views: 312

Answers (2)

Ed Morton
Ed Morton

Reputation: 203254

sed is for simple substitutions on single lines, that is all. For anything else you should be using awk for portability, efficiency, simplicity, clarity, maintainability, and most other desirable attributes of software:

$ awk 'NR%2{srvr=$NF;next} {ip=$1; sub(/.*=/,""); print ip srvr $0}' file
10.125.45.58,scope,server-1 Correctable memory error
10.125.45.58,scope,server-2 Correctable memory error

Upvotes: 0

Sundeep
Sundeep

Reputation: 23667

$ cat ip.txt 
10.125.45.58,scope, Module ID     = server-1
10.125.45.58,scope, Message       = Correctable memory error
10.125.45.58,scope, Module ID     = server-2
10.125.45.58,scope, Message       = Correctable memory error 

$ sed 'N; s/\n.*=//; s/ *Module ID.*= *//' ip.txt 
10.125.45.58,scope,server-1 Correctable memory error
10.125.45.58,scope,server-2 Correctable memory error 
  • N get next line, so the substitution works for every two lines considered together
  • s/\n.*=//; delete from newline character to last =
  • s/ *Module ID.*= *// then delete everything from Module ID upto = with optional spaces around

Upvotes: 1

Related Questions