2

I do a grep in a shell (bash) to search for some ids in many log files:

grep "100200300" my.log*

result is something like that:

my.log:Jan 17 15:04:52 100200300 ok
my.log.1:Jan 17 14:35:17 100200300 failed

Now I want to remove the filename from the output. So how can I split this text at the first occurrence of the ":" and output the second part.

1
  • 1
    Just add the -h (--no-filename) option to grep if you don't want it to output the filename when given multiple files to search Jan 17, 2016 at 14:18

3 Answers 3

3

As steeldriver commented, the preferred way is to use the -h (--no-filename) option. If your implementation of grep didn't include this option, you could use sed or cut to alter the output:

grep [OPTIONS] PATTERN [FILE...] | sed 's/[^:]*://'
grep [OPTIONS] PATTERN [FILE...] | cut -d : -f 2-

Note, however, that this solution is not general, as it breaks with filenames that contain a colon (:).

1

This will do what the title of this question ask: "split string at first occurrence of a delimiter"

#!/bin/bash
while read -r line; do
    [[ $line =~ :(.*) ]] && echo "${BASH_REMATCH[1]}"
done <<<"$(grep "100200300" my.log*)"

However, I believe that what you need is:

grep -h "100200300" my.log*

The -h option will result in file contents without filenames:

Jan 17 15:04:52 100200300 ok
Jan 17 14:35:17 100200300 failed
0

You can also do this to get rid of filenames:

cat my.log* | grep "100200300"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .