Example of a file I'm greping information in:
name : server1
description : webserver
memory : 32gb
name : server2
memory : 128gb
name : server3
description : appserver
I'm doing something like this :
cat myfile | egrep -w "name|description|memory" | awk -F" " '{print $3}' >> myfile2
In order to get back information from the second column in myfile.
Then, I format myfile2 to have information from each server on one line (using tr to replace CRLF), separated by semicolonn to import them on Excel.
myfile2:
server1;webserver;32gb
server2;128gb
server3;appserver
Problem is: when egrep doesn't match anything (like description for server2 or memory for server3), there is a gap of one row in myfile2... How can I replace it by a blank space?
Output wanted of my file2 :
server1;webserver;32gb
server2;;128gb
server3;appserver;;
I don't see the need to use
grep
on your input data. Theawk
command can do almost everything thatgrep
can. Consider the following:The components here are as follows:
-F...
sets your field delimiter, including whitespace.a[$1]=$2
populates a short-lived array with the data from each record./^memory/
executes this recipe only on the last line of each group...printf(...)
displays your output, anddelete a
lets you start fresh on the next multi-line record.You could of course compact this all onto a single line:
Is this what you need?
UPDATE
I see that you've modified your question to include sample data that is different from what the solution above supports. Here's an update that should work with the current example:
This uses a function (
outp()
) to simplify things. It uses theseen
variable to determine whether the script has seen any actual data yet (otherwise, the first match of/^name/
would generate empty output). And it continues to use thea
array to collect the important fields.It's important to note that now, instead of assuming you'll have a "memory" at the end of every record, we assume that you'll have a "name" at the beginning of every record. If this assumption is incorrect, please specify how you think you should be able to tell records from each other (i.e. where does one stop and the next one start). Blank lines are an option, for example.