RafaelGP
RafaelGP

Reputation: 1889

Bash - How to remove any empty spaces around an equal sign

I have an xml file which I'm trying to minimise using a bash script.

After removing any indentation, some part of the file looks like this:

<layer name       ="dotted_line"
align      ="topleft"
edge       ="topleft"
handcursor ="false"
keep       ="true"
url        ="%SWFPATH%/include/info_btn/dotted_line.png"
zorder     ="15"
/>

I'd like to remove any empty spaces before and after the equal sign, so it'd look like:

<layer name="dotted_line"
align="topleft"
edge="topleft"
handcursor="false"
keep="true"
url="%SWFPATH%/include/info_btn/dotted_line.png"
zorder="15"
/>

Any ideas how can achieve this?

Thanks

Upvotes: 5

Views: 2012

Answers (4)

Olivier Dulac
Olivier Dulac

Reputation: 3791

You should first try to see if xmllint --format isn't already doing everything you need:

xmllint --format OLDFILE.xml > NEWFILE.xml

The big advantage of this approach:

  • it will strip down every "cosmetic" things (extra spaces, etc). Ie it will not only replace name = value with name=value but will get rid of many other extra spaces, and indent "neatly" and tersely.
  • it knows XML, and therefore is much safer to use than any thing based on regular expressions (you CAN'T parse every xml files with regular expressions! It will work for basic xml structures, but is far from encomassing every thing an XML file can contain)

another way, if you are SURE that the name ="value" are each alone on their own line:

export _tab_="$(printf '\011')"
sed -e "s/^[ ${_tab_}]*[a-zA-Z0-9_-]\([a-zA-Z0-9_-]*\)[ ${_tab_}][ ${_tab_}]*=[ ${_tab_}][ ${_tab_}]*/\1=/"  OLDFILE.xml > NEWFILE.xml

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77155

This should work

sed 's/\s*=\s*/=/g' inputFile

Upvotes: 2

wizard
wizard

Reputation: 1554

sed -i s/\ *=\ */=/g filename

Regards

Upvotes: 7

Marc B
Marc B

Reputation: 360782

use tr?

$ echo 'hello there' | tr -d "[:space:]"
hellothere
$

Of course this'll trash ALL spaces in the file, which may be a bit too much.

Upvotes: 1

Related Questions