Search code examples
regexawkreplaceescaping

AWK replace string in file with javascript code


I want to replace a constant javascript line in awk with some code I read from a file . Interactively running this at the command line in bash works:

CUSTOM_CODE=`cat custom_code.txt`
awk -v r=$CUSTOM_CODE '{gsub(/export default function\(\) \{/,r)}1' main.js >  main-patched.js  

The problem is that if I place this 2 commands in a bash file it doesn't work anymore with the following awk error :awk: cannot open myobj (No such file or directory).

Sample files :

main.js

import asdas form "asdasdsa"
export default function() {

   let a ="asdasd"
}

custom_code.txt

const myobj = {
  aaaa:  bbb.asdasd("12345"),
  aaa2: 1
}

function myfunction(params){
 //1
    // comment
 let var1 ="a"


Solution

  • Copy/paste your script into http://shellcheck.net and it'll explain the error message you're getting (hint - always quote your shell variables) and more. It is impossible for the code you posted to work on the command line or in a script.

    The right way to do this is read the new code into an awk variable (not a shell variable) and then do a string match and replace (not *sub() as that'd fail given & in the new code and would need you to escape the regexp metachars) in the main file:

    $ awk '
        NR==FNR { new=new sep $0; sep=ORS; next }
        $0=="export default function() {" { $0=new }
        { print }
    ' custom_code.txt main.js > main-patched.js
    

    $ cat main-patched.js
    import asdas form "asdasdsa"
    const myobj = {
      aaaa:  bbb.asdasd("12345"),
      aaa2: 1
    }
    
    function myfunction(params){
     //1
        // comment
     let var1 ="a"
    
       let a ="asdasd"
    }