Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete using a different delimiter with Sed

Tags:

sed

Fairly certain I am missing something obvious!

$ cat test.txt   00 30 * * * /opt/timebomb.sh >> timebomb.log   01 30 * * * /opt/reincarnate.sh >> reincarnation.log $ sed ':timebomb:d' test.txt   00 30 * * * /opt/timebomb.sh >> timebomb.log   01 30 * * * /opt/reincarnate.sh >> reincarnation.log 

whereas

$ sed '/timebomb/d' test.txt   01 30 * * * /opt/reincarnate.sh >> reincarnation.log 

Why is it the case? Aren't a different set of delimiters supported for the d command?

like image 875
calvinkrishy Avatar asked Nov 25 '09 15:11

calvinkrishy


People also ask

How do you specify a delimiter in sed?

The delimiter of choice is a forward slash (/), which is the most commonly used delimiter. However, sed can use any character as a delimiter. In fact, it will automatically use the character following the s as a delimiter. Note that the expression has to be terminated with the delimiter.

Can we delete content in a file by using sed command?

There is no available to delete all contents of the file. How to delete all contents of the file using sed command.

How do I delete a record using sed?

Deleting line using sed To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

What is D in sed?

It means that sed will read the next line and start processing it. Your test script doesn't do what you think. It matches the empty lines and applies the delete command to them.


2 Answers

The colon preceeds a label in sed, so your sed program looks like a couple of labels with nothing happening. The parser can see colons as delimiters if preceded by the s command, so that's a special case.

like image 23
Jonathan Feinberg Avatar answered Sep 18 '22 16:09

Jonathan Feinberg


The delimiters // that you're using are not for the d command, they're for the addressing. I think you're comparing them to the slashes in the s/// command... However although both relate to regular expressions, they are different contexts.

The address (which appears before the command) filters which lines the command is applied to... The options (which appear after the command) are used to control the replacement applied.

If you want to use different delimiters for a regular expression in the address, you need to start the address with a backslash:

$ sed '\:timebomb:d' test.txt   01 30 * * * /opt/reincarnate.sh >> reincarnation.log 

(To understand the difference between the address and the options, consider the output of the command:

$ sed '/timebomb/s/log/txt/' test.txt 

The address chooses only the line(s) containing the regular expression timebomb, but the options tell the s command to replace the regular expression log with txt.)

like image 79
Stobor Avatar answered Sep 21 '22 16:09

Stobor