C.S
C.S

Reputation: 73

Remove a Line With Brackets At Beginning

I need to remove a line which starts like this:

[success] Total ....

I tried the following sed command but it didn't work

sed '/\[/d' filename > newFile

But when I greped the new file the line is still there! What is the correct command to get rid of it

Upvotes: 0

Views: 833

Answers (3)

hek2mgl
hek2mgl

Reputation: 157947

Use grep:

grep -v '^[[]' file

To match the [, I normally put it into a character class:

[]  # empty character class
[[] # character class with [ as the only item

Btw: If there are optional spaces allowed at the beginning of the line:

grep -v '^[[:blank:]]*[[]' file

Upvotes: 0

alphaGeek
alphaGeek

Reputation: 442

To delete a line starting with [ we can use this sed pattern

$ sed -E '/^\s*\[/d' filename

Say for file data3.txt having this content:

$ cat data3.txt
dont remove this line
[success] faile ... remove this line
[hola to be removed
[hola] remove this
 [hola]  remove this
[] remove thisline
this [success] Total dont remove this

You can run this command which takes care of blank/tab/space etc. at the beginning followed by [ and other text data:

$ sed '/^\s*\[/d' data3.txt
dont remove this line
this [success] Total dont remove this

Here

'/^\s*\[/d' : takes care of [ preceded by zero or more occurrences of space/tab etc.

Upvotes: 0

sjsam
sjsam

Reputation: 21955

If you are expecting to delete a line that starts with a pattern, then you should use the anchor symbol (^) in the beginning of the pattern :

sed -E '/^\[/d' filename > newFile

To accommodate blank spaces in the beginning of the pattern which is common as a result of indentation, you should do

sed -E '/^[[:blank:]]+\[/d' filename > newFile

GNU sed has an inplace-edit option realized thru -i option, so above could be replaced by

sed -Ei '/^[[:blank:]]+\[/d' filename

It seems that sed has no limits concerning file size but it is typically slow for a large file.

Upvotes: 2

Related Questions