Ubuntu – Replace string in bash script

bashcommand line

I tried the following command in my script:

find=grep "$jasper" jasperreports.properties | awk -F"reports/" '{print $2}'

Example output:

maps

I want to change this output to something else, e.g. charts. For that, I tried:

sed -i /"$find"/charts

sed is causing me problems, it needs an input file but I don't have one. Is there a way to pipe the output from grep and awk to sed?

Best Answer

-i can only be used with sed if you're passing a file, it means "inline replace". Without this, the output of sed would be written to stdout (usually the console output). With -i, it does an inline replacement, that is, doing replacements in the file itself.

The next code reads the contents of jasperreports.properties into the variable $input (line 1) and finds the string to be replaced (line 2).
On the third line, it outputs the input string and pipes it through sed for replacement. sed outputs the string to stdout which will be caught by $( and ), and therefore be stored in $input.

read input < jasperreports.properties
find=$(grep "$jasper" jasperreports.properties | awk -F"reports/" '{print $2}')
input=$(echo "$input" | sed "s/$find/charts/")

If you want to apply the changes immediately to the file:

find=$(grep "$jasper" jasperreports.properties | awk -F"reports/" '{print $2}')
sed "s/$find/charts/" -i jasperreports.properties

From man sed:

   s/regexp/replacement/
          Attempt   to   match  regexp  against  the  pattern  space.   If
          successful, replace that portion matched with replacement.   The
          replacement may contain the special character & to refer to that
          portion of the pattern space  which  matched,  and  the  special
          escapes  \1  through  \9  to refer to the corresponding matching
          sub-expressions in the regexp.
Related Question