0

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
eightShirt
  • 1,457
  • 2
  • 15
  • 29

1 Answers1

1

Since you are adding the text at the end of the line, you don't need to put the content of the existing line in your sed expression. So, you could write your command as:

sed -i -e "${LINENUMBER}s~$~ my{Text}~" file.txt

which would work irrespective of whether the line being appended to has any special characters.

The whole code can be written more efficiently as:

max=$(wc -l < file.txt)
q1=$(( max / 4 ))
q3=$(( 3 * max / 4 ))
line=$(shuf -i $q1-$q3 -n1)
sed -i -e "${line}s~$~ my{Text}~" file.txt

See also: Bash tool to get nth line from a file

codeforester
  • 39,467
  • 16
  • 112
  • 140