Trying to delete specific rows in a range Using sed

In a large file, I need to edit the text and delete comments within a certain range. For this simplified example, suppose the range starts with _start_ and ends with _end_ .

I can edit the text without problems using the following command:

 sed -i -r "/_start_/,/_end_/ s/SearchText/ReplaceText/" FileName 

Pay attention to the following (and let me know, of course, if any of my statements is inaccurate or erroneous):

  • I used -i to edit "FileName" in place, instead of writing to another file.
  • I used -r to recognize extended regular expressions (which are not shown in the simplified example above, but which seem to work correctly).
  • I used double quotes so that it handles variables correctly (also not shown in the simplified example above, but also works as expected).

This command above does exactly what I expect from her. So I moved on to the second step of my process: a very similar command to delete comment lines in this range:

 sed -i -r "/_start_/,/_end_/ /^#/ d" FileName 

This, however, has no effect: lines starting with # are not deleted. Indeed, when I execute this command myself, absolutely nothing in my file is changed or deleted - neither within the range, nor anywhere else.

In my searches on this site and elsewhere, I found a lot of instructions for deleting strings with sed (instructions that I think I follow correctly), but nothing about failure, for example, I experience.

Can someone tell me what I'm doing wrong here?

I am very new to UNIX / Linux, so I am definitely ready for alternative suggestions on how to deal with this problem. But to satisfy my disappointment, I would like to know what happened to my sed command above.

+6
source share
2 answers

The best source of information is often a man page. You can contact him with the man sed command.

d takes the address range according to the man page. An address can be a number, a / regexp /, or a number of other things. An address range is a single address or two addresses, separated by a comma. You tried to use a range of addresses, and then an address.

As 1_CR pointed out, you can work using the block instead:

 sed -i -r "/_start_/,/_end_/ {/^#/ d}" FileName 

The block accepts a range of addresses, and each command again accepts a range of addresses, so you can combine regular expressions.

+5
source

You need to change

 sed -i -r "/_start_/,/_end_/ /^#/ d" FileName 

to

 sed -i -r "/_start_/,/_end_/{/^#/d}" FileName 
+2
source

Source: https://habr.com/ru/post/956680/


All Articles