Reputation: 13
I'm currently writing a script that will remove directory names from file if not found in system. However, I cannot get my sed command to work.
Current command:
sed -i '/"$row"/d' DirtoDelete.txt
$row
expands to //maindir/subdir/testing
<--- directory being deleted
but I keep getting the following error:
sed: -e expression #1, char 27: expected newer version of sed
Any ideas what's going on here? Or is there a better way to escape those leading forward slashes?
Upvotes: 1
Views: 623
Reputation: 158240
You can use a different delimiter:
sed -i "\#${row}#d" DirtoDelete.txt
We are using #
as the delimiter here because $row
does not contain a #
. (If you can't ensure that for your input data use something else). Furthermore you need to escape the starting delimiter in this case: \#
:
From POSIX sed:
In a context address, the construction "\cBREc", where c is any character other than backslash or newline, shall be identical to "/BRE/". If the character designated by c appears following a backslash, then it shall be considered to be that literal character, which shall not terminate the BRE. For example, in the context address "\xabc\xdefx", the second x stands for itself, so that the BRE is "abcxdef".
Upvotes: 0
Reputation: 5768
You do not have to abuse regular expressions for literate text substitution. awk index
function finds substrings.
$ cat r
d="$1"; shift
awk -v d="$d" '{
s = $0
while (i = index(s, d))
s = substr(s, 1, i - 1) substr(s, i + length(d))
print s
}' "$@"
Usage:
$ echo '/a/b = /a/b' | sh r 'a/b'
/ = /
Upvotes: 1
Reputation: 247210
I know there's a duplicate of this question. Nevertheless:
If you change delimiters, you'll have to escape those in the string, so just bite the bullet and escape the slashes:
$ row=//maindir/subdir/testing
$ echo "${row//\//\\/}"
\/\/maindir\/subdir\/testing
$ echo $'first\nline with '"$row"$'\nlast'
first
line with //maindir/subdir/testing
last
$ echo $'first\nline with '"$row"$'\nlast' | sed "/${row//\//\\/}/d"
first
last
See Shell Parameter Expansion in the bash manual.
Upvotes: 2