0

I did a little code that works with sed in a script and I need to replace the line 5 in file.txt with a random generated characters as shown bellow but I will write in the below code just one set of characters to simplify it.

var='6C|&}|X_5gaJ|^s U/>+c,G>$Xe]t^</$H-$K;1?Im~bk]_z3gJo@1,y`eVb{kt?' #those characters are always changing in my code with another command

sed -i "5s|.*|$var|" file.txt

I tried to work with | instead of / but even that doesn't work because as you can see in the set of the characters in var it contains | and an error occurs.

So is there any way to solve this issue without modifying the characters in the value of var? because as I said above, it generated every time.

Holy semicolon
  • 868
  • 1
  • 11
  • 27
  • 1
    no, it is not possible in `sed` to do so without changing `var`, you have escape metacharacters first.. see https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed ... – Sundeep Jan 13 '20 at 04:31
  • Your latest edit makes this no longer technically a duplicate, but what response other than the previous comment's do you expect? If your random characters are strictly printable you could use an unprintable control character as the separator, but I don't know how portable that is, and your question currently seems to imply no restrictions on the random string (though your example vaguely suggests otherwise). – tripleee Jan 13 '20 at 04:54
  • And sttill, if your generated string contains `\ ` or `&`, those have a special meaning in the replacement string, and will still need to be escaped. – tripleee Jan 13 '20 at 04:57
  • Maybe switch to Perl, which offers enough oomph and syntactic sugar to work around this problem with a reasonable effort if you really can't escape the string. – tripleee Jan 13 '20 at 05:00
  • @tripleee actually my variable takes it's value from a txt folder ` var= `sed -n ${j}p slats.txt`; ` I think there is a way to precede every special character with it's escape character. – Holy semicolon Jan 13 '20 at 05:05
  • 1
    Yeah, the duplicate shows you how to do that. Also prefer modern `$(command substitution)` shell syntax over backticks, and check the spelling of "its". – tripleee Jan 13 '20 at 05:11
  • @tripleee Yeah I will see how to do it, and I am going to take your advice. – Holy semicolon Jan 13 '20 at 05:15

0 Answers0