0

How to replace below text with an empty line in a config file?

# + : STANDANRD\ADMIN_USERS_ONLY : ALL
  • 1
    The only tricky thing I see here is that you will need to escape the backslash - see for example [What characters do I need to escape when using sed in a sh script?](https://unix.stackexchange.com/questions/32907/what-characters-do-i-need-to-escape-when-using-sed-in-a-sh-script) – steeldriver May 08 '20 at 21:29

1 Answers1

0
sed -i 's/# + : STANDANRD\\ADMIN_USERS_ONLY : ALL//g' config_file

should do the trick. Note the double backslash which is important since a backslash followed by a character has a special meaning to the regex parser. These meta characters are shortcuts for things like a whitespace (\s), an alphanumeric character (\w) or in the case of \A the beginning of a string (the Regular Expression Wikipedia article has a table summarizing the most popular meta characters). Since backslash has this special meaning you have to type a double backslash if you want to match a single backslash in your file.

Example output on CentOS 7:

[tux@centos7 ~]$ cat config_file 
# + : STANDANRD\ADMIN_USERS_ONLY : ALL foo
[tux@centos7 ~]$ sed -i 's/# + : STANDANRD\\ADMIN_USERS_ONLY : ALL\(.*\)/\1/g' config_file
[tux@centos7 ~]$ cat config_file 
 foo
Martin Konrad
  • 2,090
  • 2
  • 16
  • 32
  • It worked!!! Thanks a lot Martin!!! i googled and tried many complex sed's you did it simple...... i have a problem here the sed you gave removes entire line even if it has content after : ALL your suggestion pls – Harshita Reddy May 09 '20 at 20:01
  • You can capture part of the line with a so called capture group (in parantheses). You can insert this captured string by inserting a "back references" into the replacement string: `sed -i 's/# + : STANDANRD\\ADMIN_USERS_ONLY : ALL\(.*\)/\1/g' config_file`. The parantheses need to be quoted here [since they have special meaning for Bash](https://stackoverflow.com/a/2188369/7583635). – Martin Konrad May 10 '20 at 01:21
  • i tried but it still removes the other part of the text after : ALL – Harshita Reddy May 10 '20 at 19:48
  • Hmm, works fine for me on Ubuntu 20.04 with Bash. Which system and shell are you using? Could you please also share the full line in the file before and after replacing? – Martin Konrad May 11 '20 at 02:30
  • am using RHEL 7 with bash – Harshita Reddy May 11 '20 at 21:04