0

I have a file with lines containing this format:

fieldA=value1, fieldB=value2, fieldC=value3, fieldD=value4, fieldE=value5

I am interested in fieldA, fieldB, fieldD. However, fieldC may or may not be present, therefore I cannot use something like:

grep "field" * | awk -F"," '{print $1, $2, $4}'

My end goal is to have output like this, all in one line:

fieldA=value1, fieldB=value2, fieldD=value4

I tried using grep -E, but it outputs those fields in different lines, and the association between the fields breaks.

grep -o -E "field1_=\w*|field2_=\w*|field3_=\w*"
2
  • 1
    are those 3 fields' name (A,B and D) fixed? or everything is dynamic? Commented Jan 16, 2013 at 0:07
  • Kent, all the fields are fixed (A, B,..D), but the values are not. Commented Jan 16, 2013 at 1:30

2 Answers 2

1

if you know the field name of A,B,D grep and xargs could do the job. ( awk/sed could do it for sure)

grep -Po "fieldA=[^,]*|fieldB=[^,]*|fieldD=[^,]*" file|xargs -n3

that gives you:

fieldA=value1 fieldB=value2 fieldD=value4

if you want the comma in output:

grep -Po "fieldA=[^,]*,|fieldB=[^,]*,|fieldD=[^,]*" file|xargs -n3
Sign up to request clarification or add additional context in comments.

Comments

0

Is a sed solution acceptable?

sed 's/^\([^ ]* [^ ]*\).*\(fieldD=[^,]*\).*/\1 \2/' filename

1 Comment

Thank you this helped. I was able to come up with a similar solution with sed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.