bashshellsedfind

Sed replace single text with content of file


I have a question regarding using sed.

I have a JSON file and I want to get it inserted in another file.

What I'm trying is to get all the contents of the .json file which contains 4500 lines, and replace the specific text in my HTML:

{DATA_INPUT}

I have been using

DATA_JSON=$(echo "$(<data.json)")

sed -i "s/{DATA_INPUT}]{\}/${DATA_JSON}{\}/g" convert.html

But seems is not working,

And I'm getting

/bin/find: Argument list too long

I have also tried:

DATA_JSON=$(echo "$(<data.json)")
find . -maxdepth 1 -type f -name 'convert.html' \
    -exec sed -n "s/{DATA_INPUT}/${DATA_JSON}/g" {} \;

But getting:

 /bin/sed: Argument list too long

I'm trying to integrate this with Bash.

So basically I'm trying to get all the contents from the file and replace the text that I have in convert.html


Solution

  • sed already knows how to insert the contents of a file.

    sed -i '/{DATA_INPUT}/r data.json' convert.html
    

    In isolation, this will insert the contents of data.json on the following lines after the match. If you want to also manipulate the match, perhaps try something like

    sed '/{DATA_INPUT}/!b;s///;r data.json' convert.html
    

    (probably leave out the -i until you are satisfied that you have a working script) but this is still rather clunky and doesn't work correctly if you want to preserve the context around the {DATA_INPUT} token and keep it on either side of the inserted contents.

    Perhaps it's more fruitful to try e.g. Awk or Perl, which are somewhat less read-only;

    awk 'NR==FNR { gsub(/&/, "\\\\&"); lines = lines (lines ? "\n" : "") $0; next }
        /\{DATA_INPUT\}\{\}/ { sub(/\{DATA_INPUT\}/, lines) }
       1' data.json convert.html >new.html