0

I want to edit a file. I want to search for a string and delete the line containing the string and 19 lines before it.

I found a similar question on another site (the topic is closed now), and the answer given was to use the following ed commands (The first command was to delete X lines before the PATTERN and the 2nd command deletes X lines after the PATTERN);

ed -s file <<< $'g/PATTERN/-X,.d\n,p'
ed -s file <<< $'g/PATTERN/.,+Xd\d,p'

I have tried the first command and it works, but I do not understand the meaning of the \n and the \d in the first and 2nd command respectively. I think the \n might be "next line", but why is this necessary if you are going to print (,P) all lines anyway?

1 Answers1

2

You can test the command passed to "ed" with a simple echo:

 $ echo $'g/PATTERN/-X,.d\n,p'
 g/PATTERN/-X,.d
 ,p

So in fact the \n only indicates the end of the first command, and is replaced within your shell. This has no meaning for ed but for your shell.

As you said g/PATTERN/-X,.d removes all the line from -X line to current position of the lines matched by PATTERN

,p show all the lines from the file

In the second command, the \d is just an error. And you should read it as \n.

Adam
  • 17,838
  • 32
  • 54