Home > Blockchain >  Replace string in a file using bash
Replace string in a file using bash

Time:10-28

I am trying to use the sed functionality of bash scripting to find and replce the content in a file. Not sure if my approach is correct or not but I dont want to go with regex.

Input:

 <if property="headless">
        <VMArg name="-Djava.awt.headless=true"/>
    </if>

    <VMArg name="-Dfile.encoding=UTF-8"/>
    <VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
    <VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>

Expected:

 <if property="headless">
        <VMArg name="-Djava.awt.headless=true"/>
    </if>
This is the replaced text
    <VMArg name="-Dfile.encoding=UTF-8"/>
    <VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
    <VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>

Trying to develop something like below but unfortunately its not working.

#!/bin/bash
find='<if property="headless">
        <VMArg name="-Djava.awt.headless=true"/>
    </if>

    <VMArg name="-Dfile.encoding=UTF-8"/>'

replace='<if property="headless">
        <VMArg name="-Djava.awt.headless=true"/>
    </if>

    <VMArg name="-Dfile.encoding=UTF-8"/>'

sed "s/$find/$replace/g" filename.input

Error:

sed: -e expression #1, char 7: unterminated `s' command

CodePudding user response:

The answer is: sed -i -e '1h;2,$H;$!d;g' -Ee 's/(<VMArg name="-Djava.awt.headless=true"\/>\n\s <\/if>)/\1\nThis Is replaced text/' file

Working solution:

$ cat file
<if property="headless">
        <VMArg name="-Djava.awt.headless=true"/>
    </if>

    <VMArg name="-Dfile.encoding=UTF-8"/>
    <VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
    <VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>

$ cat file  | sed -e '1h;2,$H;$!d;g' -Ee 's/(<VMArg name="-Djava.awt.headless=true"\/>\n\s <\/if>)/\1\nThis Is replaced text/'
<if property="headless">
        <VMArg name="-Djava.awt.headless=true"/>
    </if>
This Is replaced text

    <VMArg name="-Dfile.encoding=UTF-8"/>
    <VMArg name="-Djava.util.logging.config.file=$VDISTDIR/system/conf/logging.properties"/>
    <VMArg name="-Dlog4j.configurationFile=file:///$VDISTDIR/system/conf/log4j2.yaml"/>```
  • Related