如何从 Unix 命令行在 XML 文件中添加换行符?

Nat*_*ong 6 unix command-line

我有一个很大的 XML 文件。从 Unix 命令行,我想在每个>.

我曾尝试为此使用 sed,但没有运气:

sed -i '' -e's/>/>\n/' file.xml
Run Code Online (Sandbox Code Playgroud)

这只是插入字母n,而不是换行符。我也试过\r\r\n

我怎样才能做到这一点?

(仅供参考 - 我在 OSX 中使用 zshell。)

Red*_*ick 16

脚本

使用indentxml file.xml查看,indentxml file.xml > new.xml进行编辑。

indentxml 在哪里

#!/usr/bin/perl
#
# Purpose: Read an XML file and indent it for ease of reading
# Author:  RedGrittyBrick 2011. 
# Licence: Creative Commons Attribution-ShareAlike 3.0 Unported License
#
use strict;
use warnings;

my $filename = $ARGV[0];
die "Usage: $0 filename\n" unless $filename;

open my $fh , '<', $filename
  or die "Can't read '$filename' because $!\n";
my $xml = '';
while (<$fh>) { $xml .= $_; }
close $fh;

$xml =~ s|>[\n\s]+<|><|gs;                       # remove superfluous whitespace
$xml =~ s|><|>\n<|gs;                            # split line at consecutive tags

my $indent = 0;
for my $line (split /\n/, $xml) {

  if ($line =~ m|^</|) { $indent--; }

  print '  'x$indent, $line, "\n";

  if ($line =~ m|^<[^/\?]|) { $indent++; }             # indent after <foo
  if ($line =~ m|^<[^/][^>]*>[^<]*</|) { $indent--; }  # but not <foo>..</foo>
  if ($line =~ m|^<[^/][^>]*/>|) { $indent--; }        # and not <foo/>

}
Run Code Online (Sandbox Code Playgroud)

解析器

当然,规范的答案是使用适当的 XML 解析器。

# cat line.xml
<a><b>Bee</b><c>Sea</c><d><e>Eeeh!</e></d></a>

# perl -MXML::LibXML -e 'print XML::LibXML->new->parse_file("line.xml")->toString(1)'
<?xml version="1.0"?>
<a>
  <b>Bee</b>
  <c>Sea</c>
  <d>
    <e>Eeeh!</e>
  </d>
</a>
Run Code Online (Sandbox Code Playgroud)

公用事业

但也许最简单的是

# xmllint --format line.xml
<?xml version="1.0"?>
<a>
  <b>Bee</b>
  <c>Sea</c>
  <d>
    <e>Eeeh!</e>
  </d>
</a>
Run Code Online (Sandbox Code Playgroud)

  • 当然,像往常一样,任何使用正则表达式解析 XML 的尝试都是徒劳的。永远不要忘记 `&lt;something attribute="&lt;foo&gt;"&gt;` 是有效的 XML,字符串类型属性可以将任何文字字符串作为值。http://www.w3.org/TR/xml/#sec-attribute-types (3认同)