0

I am struggling with grep, awk and sed with this issue. I have an XML with lines like these:

<field type="float8" name="something" database_fieldname="SHORT" allowsnull="false"/>
<field type="float8" name="LONG" database_fieldname="LONG" allowsnull="false"/>

I want to isolate those lines where the values for name= and database_fieldname= are identical, and, if that is the case, remove the entire field database_fieldname=. Expected output:

<field type="float8" name="something" database_fieldname="SHORT" allowsnull="false"/>
<field type="float8" name="LONG" allowsnull="false"/>
  • XML files should be used/search/build with XML tools (xmllint/xmlstarlet/xsltproc). You should move this question to stack overflow. – Archemar Oct 3 '18 at 12:21
0

awk approximation to a solution:

awk '
        {match ($0, / name="[^"]*"/)
         R1 = RSTART
         L1 = RLENGTH
         match ($0, / database_fieldname="[^"]*"/)
         R2 = RSTART
         L2 = RLENGTH
         if (substr ($0, R1+7, L1-8) == substr ($0, R2+21, L2-22)) sub (substr ($0, R2, L2), "")
        }
1
' file
<field type="float8" name="something" database_fieldname="SHORT" allowsnull="false"/>
<field type="float8" name="LONG" allowsnull="false"/>

It matches both target fields, extracts their values for comparison, and, if equal, substitutes the second entirely with the empty string.

| improve this answer | |
0

You could use a backreference in your search pattern:

sed -e 's/name="\(.*\)" database_fieldname="\1"/name="\1"/' <input>
| improve this answer | |

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.