SedまたはPerlを使用して改行文字を削除する方法

SedまたはPerlを使用して改行文字を削除する方法

次の行を含む巨大なXMLデータファイルがあります。

<fonts> some of the data </fonts>
<fonts> some of the data </fonts>
<fonts> some of
 the data </fonts>
<fonts> some of the data </fonts>
<fonts> some of the data </fonts>

その間に改行文字が来ます...

$>uname -a
SunOS ******* 5.11 SunOS_Development

ベストアンサー1

XMLファイルが与えられた場合file.xml

<?xml version="1.0"?>
<root>
  <fonts> some of the data </fonts>
  <fonts> some of the data </fonts>
  <fonts> some of
the data </fonts>
  <fonts> some of the data </fonts>
  <fonts> some of the data </fonts>
</root>

normalize-spacesXMLStarletを使用して、すべてのノードにXPath機能を適用できます。fonts

$ xmlstarlet ed -u '//fonts' -x 'normalize-space()' file.xml
<?xml version="1.0"?>
<root>
  <fonts>some of the data</fonts>
  <fonts>some of the data</fonts>
  <fonts>some of the data</fonts>
  <fonts>some of the data</fonts>
  <fonts>some of the data</fonts>
</root>

fontsこれにより、サイドスペースが削除され、すべてのノードの他のすべてのタイプのスペースが単一のスペースに置き換えられます。

削除するだけですか?改行文字fontsノードのデータ:

$ xmlstarlet ed -u '//fonts' -x 'translate(., "'$'\n''", "")' file.xml
<?xml version="1.0"?>
<root>
  <fonts> some of the data </fonts>
  <fonts> some of the data </fonts>
  <fonts> some of the data </fonts>
  <fonts> some of the data </fonts>
  <fonts> some of the data </fonts>
</root>

$'\n'これはリテラルの改行で拡張されるシェルに依存します。

おすすめ記事