I have about 2000 files that I need lines added to the beginning and end of.
I need these lines at the beginning of each files:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
I also need this to be the last line of each file:
</urlset>
These files are all in the same folder and are all .xml files.
I'm thinking the best and fastest way to do this would be via command line or perl but am really not sure. I've seen a few tutorials on doing this but I think all the characters that are in the lines I need inserted are whats messing it up. Any help would be greatly appreciated. Thanks!
Since you asked for Perl...
Version that loads entire file into memory:
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
Version that only reads one line at a time:
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
Note: eof is not the same as eof().
Note: close(ARGV) causes the line numbers to reset.
For Perl you can use Tie::File to do it easily.
#!/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;
}
Save to whatever you want, then run it as perl whatever_you_named_it path/to/files/*.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With