22

I have a logfile with timestamps in it. Occasionally there are multiple timestamps in one line. Now I would like to remove all of the timestamps from a line but keep the first one.

I can do s/pattern//2 but that only removes the second occurrence and sed doesn't allow something like s/pattern//2-.

Any suggestions?

1
  • I should've told that it's the sed of busybox. Sorry for that. Aug 8, 2011 at 12:08

4 Answers 4

8

With GNU sed:

sed 's/pattern//2g'

The 2 specifies that the second pattern and all the restg should remove. So this will keep the first one.

3
  • 2
    Which Cygwin has (a port of, apparently) and MacOS does not. Achh! This solution is so much more elegant. Jun 2, 2017 at 4:03
  • I couldn't get this to work on macos with builtin sed, and gsed. With builtin sed, it would return sed: 1: "s/^ *$//2g": more than one number or 'g' in substitute flags - with gsed, it would be as if nothing happened.
    – balupton
    Dec 2, 2021 at 8:09
  • @balupton that's not available in non-GNU sed; and for the gsed you are expecting substituting second to last empty line (including space characters only lines) within that line, which definitely there is no more than one line in a line. Dec 2, 2021 at 8:20
8

This should work (replace _ by something else should it clash with your logs):

sed -e 's/pattern/_&/1' -e 's/\([^_]\)pattern//g' -e 's/_\(pattern\)/\1/'
1
  • 2
    if you're ever wanting a unique delimiter, use \n.
    – mikeserv
    Dec 19, 2014 at 13:35
5
sed -e ':begin;s/pattern//2;t begin'

or without the sed goto:

sed -e 's/\(pattern\)/\1\n/;h;s/.*\n//;s/pattern//g;H;g;s/\n.*\n//'

The generic solutions to remove from the nth (3 for example) position are:

sed -e ':begin;s/pattern//4;t begin'
sed -e 's/\(pattern\)/\1\n/;h;s/.*\n//3;s/pattern//g;H;g;s/\n.*\n//'
2

A slight variation on @jillagre's answer (modified for robustness) could look like:

sed 's/p\(attern\)/p\n\1/;s///g;s/\n//'

...but in some seds you may need to replace the n in the right-hand side of the first s///ubstitution statement with a literal \newline character.

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.