Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed to match a pattern and deleting from the line to the end of the file

I'm trying to match a pattern from piped input and/or a file, and then remove from the matched lines to the end of the file, inclusive. I've looked everywhere, but can't seem to find an expression that would fit my needs.

The following expression allows me to remove to the beginning of the stream, including the matched pattern:

sed -e '1,/Files:/d' 

Given some sample data:

Blah blah blah Foobar foo foo Files:  somefiles.tar.gz 1 2 3  somefiles.tar.gz 1 2 3  -----THIS STUFF IS USELESS----- BLEH BLEH BLEH BLEH BLEH BLEH 

Running the above expression produces:

Files:  somefiles.tar.gz 1 2 3  somefiles.tar.gz 1 2 3  -----THIS STUFF IS USELESS----- BLEH BLEH BLEH BLEH BLEH BLEH 

I would like to achieve a similar effect, but in the opposite direction. Using the output from the previous expression, I want to remove from -----THIS STUFF IS USELESS----- to the end of the file, inclusive. It should produce (after going through the first expression):

Files:  somefiles.tar.gz 1 2 3  somefiles.tar.gz 1 2 3 

I'm also open to using any other tools, as long as it is available on any other POSIX system and does not use version specific (e.g. GNU-specific) options.

The actual text can be found here: http://pastebin.com/CYBbJ3qr Note the change from -----THIS STUFF IS USELESS----- to -----BEGIN PGP SIGNATURE-----.

like image 573
Albert H Avatar asked Dec 26 '12 22:12

Albert H


People also ask

How do you delete a pattern in the file using sed?

Just like in VIM, we will be using the d command to delete specific pattern space with SED. To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command.

How do you delete a line in a file 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.

How do you put something at the end of a line using sed?

Using a text editor, check for ^M (control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.


1 Answers

why not

 sed '/^-----THIS STUFF IS USELESS-----$/,$d' file 

In a range expression like you have used, ',$' will specify "to the end of the file"

1 is first line in file,  $ is last line in file. 

output

Files:  somefiles.tar.gz 1 2 3  somefiles.tar.gz 1 2 3 


With GNU sed, you can do

sed '/^-----THIS STUFF IS USELESS-----$/Q' file 

where Q is similar to q quit command, but doesn't print the matching line

like image 180
shellter Avatar answered Sep 21 '22 21:09

shellter