【问题标题】:Inserting lines at the beginning and end of multiple files在多个文件的开头和结尾插入行
【发布时间】:2012-11-02 00:15:20
【问题描述】:

我有大约 2000 个文件需要在开头和结尾添加行。

我需要在每个文件的开头这些行:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

我还需要将其作为每个文件的最后一行:

</urlset>

这些文件都在同一个文件夹中,都是.xml文件。

我认为最好和最快的方法是通过命令行或 perl,但我真的不确定。我已经看过一些关于这样做的教程,但我认为我需要插入的行中的所有字符都搞砸了。任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: perl command-line


    【解决方案1】:

    既然你要求 Perl...

    将整个文件加载到内存中的版本:

    perl -i -0777pe'
       $_ = qq{<?xml version="1.0" encoding="UTF-8"?>\n}
          . qq{<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n}
          . $_
          . qq{</urlset>\n};
    ' *.xml
    

    一次只读取一行的版本:

    perl -i -ne'
       if ($.==1) {
          print qq{<?xml version="1.0" encoding="UTF-8"?>\n},
                qq{<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n};
       }
       print;
       if (eof) {
          print qq{</urlset>\n};
          close(ARGV);
       }
    ' *.xml
    

    注意:eofeof() 不同。
    注意:close(ARGV) 会导致行号重置。

    【讨论】:

    • -0777pe 是什么意思?是换$/吗?
    • -0777 -p -e-0777 确实改变了$/,导致 Perl 将整个文件视为一行。见perlrun
    【解决方案2】:

    对于 Perl,您可以使用 Tie::File 轻松完成。

    #!/usr/bin/env perl
    use utf8;
    use v5.12;
    use strict;
    use warnings;
    use warnings  qw(FATAL utf8);
    use open      qw(:std :utf8);
    
    use Tie::File;
    
    for my $arg (@ARGV) {
      # Skip to the next one unless the current $arg is a file.
      next unless -f $arg;
    
      # Added benefit: No such thing as a file being too big
      tie my @file, 'Tie::File', $arg or die;
    
      # New first line, will become the second line
      unshift @file, '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    
      # The real first line.
      unshift @file, '<?xml version="1.0" encoding="UTF-8"?>';
    
      # Final line.
      push @file, '</urlset>';
    
      # All done.
      untie @file;
    }
    

    保存到您想要的任何内容,然后以perl whatever_you_named_it path/to/files/* 运行它。

    【讨论】:

    • 我喜欢这个可读性很强的解决方案,尽管它由于Tie::File 的开销而相当慢。
    【解决方案3】:

    使用 sed:

    sed -i -e '1i<?xml version="1.0" encoding="UTF-8"?>\
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' \
    -e '$a</urlset>' *.xml
    

    【讨论】:

      【解决方案4】:

      尝试在 中执行此操作,我只使用 和简单的

      for file in *.xml; do
          {
              echo '<?xml version="1.0" encoding="UTF-8"?>
                  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
              cat "$file"
              echo "</urlset>"
          } > /tmp/file$$ &&
          mv /tmp/file$$ "$file" 
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-05
        • 2023-03-11
        • 2011-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多