0

I have a list of files which I would like to bulk edit using sed.

  1. Replace the first line of all the files in a directory with output of header.txt
  2. Amend the output of footer.txt to all the files.

Say I have to replace the current XML header on all the files in a folder as below:

From:

<?xml version="1.0" encoding="utf-8"?>

To:

<?xml version="1.0" encoding="utf-8"?>
<Container xmlns="http://www.arun-test.com/1.0">
  <APIHeader version="2.0" exportTime="Sun Oct 11 09:42:25 EST 2020"></APIHeader>

Also I have to add the output of a file footer.txt content to all the files in a directory.

Please guide me through the correct steps.

thanasisp
  • 8,122
AArun
  • 1

2 Answers2

0

You could use sed's r command to read and insert the header and footer files at addresses 1 and $ respectively.

Assuming GNU sed (based on your 'linux' tag), and that the number of files in the directory is not large enough to exceed the maximum command length, then

sed -i -e '1r header.txt' -e '1d' -e '$r footer.txt' dir/*

will add the contents of header.txt and footer.txt to each file in dir.

Note that -i causes the original files to be overwritten - you would be wise to test it with -s in place of -i and/or to make backups by changing -i to something like -i.bak.

steeldriver
  • 81,074
0

Assuming you want to remove the first line from all files and insert the header, and append the footer at the end, using bash shell:

for f in *.xml; do
    tmp=$(mktemp)
    ( 
        cat header.txt
        tail -n +2 "$f"
        cat footer.txt
    ) > "$tmp" && mv "$tmp" "$f"
done
thanasisp
  • 8,122