1

How can i replace the following text in a file in linux with a different line

Current :

0 22 * * * /scripts/application_folder_backup.sh >> /var/log/application_folder_backup.log

Replacement line : #line_removed

I tried using sed but my text in the file already has a / which is causing problems. I tried storing the string in a variable too. But it doesn't work

#!/bin/bash

var="0 22 * * * /scripts/application_folder_backup.sh >> /var/log/application_folder_backup.log"

sed -i -e 's/$var/#line_removed/g' /tmp/k1.txt

exit

anishsane
  • 20,270
  • 5
  • 40
  • 73
Karthik Rao V
  • 61
  • 1
  • 7

2 Answers2

1

Just / is not a problem here, even * or all the special regex meta characters will be a problem for sed since it uses only regex for search patterns.

Better to use this non-regex based awk command:

awk -v var="$var" 'index($0, var) { $0 = "#line_removed" } 1' file

#line_removed

index function in awk uses plain text search instead of a regex based search.

anubhava
  • 761,203
  • 64
  • 569
  • 643
-1

I suggest previous to feed the contents of $var to the sed script, to escape all the / chars to be \/, as in:

var_esc=$(echo "$var" | sed 's/\//\\\//g')

But the sed expression gets very complicated (you must use single quotes, if you don't want to double \ chars, as double quotes do interpret also the backslashes.

Another thing that could simplify the expression is to use the possibility of change the regexp delimiter (with using a different char to begin it) as in:

var_esc=$(echo "$var" | sed 's:/:\/:g')

The idea is to, before substituting the $var variable, to escape all the possible interferring chars you can have (you don't know a priory if there are going to be, as you are using a variable for that purpose) and then substitute them in the final command:

sed "s/$var_esc/#line_removed/g"

Finally, if you don't want to substitute the line, but just to erase it, you can do something like this:

sed "/$var_esc/d"

and that will erase all lines that match your $var_esc contents. (this time I believe you cannot change the regexp delimiter, as the / introduces the matching line operator --- d is the command to delete line in the output)

Another way to delete the line in your file is to call ex directly and pass the editor command as input:

ex file <<EOF          <-- edit "file" with the commands that follow until EOF is found.
/$var_esc              <-- search for first occurrence of $var_esc
d                      <-- delete line
w                      <-- write file
EOF                    <-- eof marker.
Luis Colorado
  • 10,974
  • 1
  • 16
  • 31
  • Sorry, It should be polite to explain the reasons of a downvote, as not only the question has been answered but also it seems to be the selected answer. I want also to learn why my answers don't seem to be right for everybody. – Luis Colorado Feb 18 '17 at 08:57