0

I need to remove a specific pattern from a text file.

check this (2005)
right now (2003)

I tried using sed for this purpose, however I receive an error.

sed 's/\s(.*)//d' file.txt

I want to remove the following patterns from the file:

 (2005)
 (2003)

The one space character before the bracket also needs to be removed.

1

The substitute command s does not have a d flag.

There's a d (delete) command though:

sed '/ (.*)$/d' file.txt

This would delete all lines from the input that contains a parenthesised string at the end of the line, preceded by a space (which is not what you want to do).

Instead, drop the flag and do an ordinary substitution with nothing:

sed 's/ (.*)$//' file.txt

To restrict the deletion to only parentheses that contain four-digit numbers:

sed 's/ ([0-9]\{4\})$//' file.txt
0

You can just do this:

sed 's| (....)||g' file.txt

That will remove four occurrences of any character within parentheses with each . representing one character. It also removes the space before the bracket.

If there are several characters between the parentheses then you can use a glob:

sed 's| (.*)||g' file.txt

Once you have confirmed that it does what you want, add i to edit the file in-place.

sed -i 's| (....)||g' file.txt

sed -i 's| (.*)||g' file.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.