I read some Q&A here about it but nothing worked for me. I understand special characters are a problem when using sed
, but how to deal with it without know if they are present in the pattern?
In my specific case, I have a file (file.txt
) like follows:
my line 1.
my line two.
...
this is [ -f another line ]
I am trying to insert a text (my{Text}
) in the end of a random line.
MAX=$(wc -l < file.txt)
Q1=$(expr $MAX / 4)
Q3=$(( 3 * $MAX / 4 ))
LINENUMBER=$(shuf -i $Q1-$Q3 -n1)
LINE="$(head -n $LINENUMBER file.txt | tail -1)"
sed -i -e "${LINENUMBER}s~$LINE~$LINE my{Text}~g" file.txt
This code works well when $LINE
is not the line that contains this is [ -f another line ]
. In this case $LINE my{Text}
is not replacing $LINE
.
So how to handle with a random pattern that may need to be escaped using sed
?
I am using GNU bash 4.3.11(1) and sed (GNU sed) 4.2.2.