Executing sed command inside a bash script

I want to run commands inside a bash script.

An example is

I want to pass the command in a string as regexp as an argument to the script, then run sed on the bash variable

sed.sh regexp
 sed.sh "-i \"s/<p>//g\""
 

then call

sed "$regexp" $fl
 

Here is part the code I have written

    fraw="$fl"
     if [ -n "$arg_sedexp" ]; then
      regexp="$arg_sedexp"
      if [[ "$arg_sedexp" == *"-i"* ]]; then
        echo "sed "$regexp" $fl"
        sed "$regexp" $fl
      else
        fsed="${odr}/${flb}--sed.txt"
        fraw="$fsed"
        sed "$regexp" $fl > $fsed
      fi 
    fi

What is your question?

quotes-inside-quotes is usually a bad idea. The shell doesn't handle them - or any other shell syntax - in variables as a security measure. You can force it to do so, but that often ends up evaluating a lot of things you don't want it to.

There's probably a way to do this without resorting to quotes-in-quotes. What, exactly, are you trying to accomplish? Don't say "quotes inside quotes", don't say "passing arguments", etc, etc. What is your ultimate goal?

By my best guess, I'd do something like this:

#!/bin/bash

while [ "$#" -gt 0 ]
do
case "$1" in
-*)    # Collect all -i, -r, etc arguments
        SEDARGS="$SEDARGS $1"
        shift
        ;;
*)    break ;;
esac
done

REGEX="$1"

if [ -z "$SEDARGS" ]
then
        echo sed "$REGEX" "$FILE"
else
        echo sed $SEDARGS "$REGEX" "$FILE"
fi

Run it like:

./myscript.sh -r -i "regex"

No need for quotes-in-quotes as it takes the arguments as given.

2 Likes

Have done it this way as suggested.

./myscript.sh -r -i "regex"