Sure, use bash parameter substitution to escape the troublesome slash character:
comment () { sed -i "/${1//\//\\/}/ s/^/${2//\//\\/} /" "$3"; }
Notes:
- You need to protect slashes in both the pattern and the replacement parts.
- if your search is anchored, using "g" is pointless because the pattern can match at most once.
- quote all your variables: if the filename contains a space, your code breaks.
- one line functions require a semicolon before the closing brace.
Demo
$ cat file
test/1/
test/2/
test/3/
$ comment 'test/2' '//' file
$ cat file
test/1/
// test/2/
test/3/
I realized I'm not escaping regex special characters. The safest way is to escape any non-alphanumeric characters:
comment () {
local pattern=$(sed 's/[^[:alnum:]]/\\&/g' <<<"$1")
local replace=${2//\//\\/}
local file=$3
sed -i "/$pattern/ s/^/$replace /" "$file"
}
But since you want to do plain text matching, sed is probably not the best tool:
comment() {
perl -i -pse '$_ = "$leader $_" if index($_, $search) > -1' -- \
-search="$1" \
-leader="$2" \
"$3"
}