Better with sed
:
sed -n 's/^\[one]: //p' < example.txt
With GNU grep
with support for recent PCRE, you can also do:
grep -Po '^\[one]: \K.*' < example.txt
Or
grep -xPo '\[one]: \K.*' < example.txt
In any case, note that in most shells, [...]
are glob operators. In grep [myword]
, [myword]
is expanded to the list of files that match that, that is any file in the current directory whose name is m
, y
, w
, o
, r
or d
(and if there's none, depending on the shell, the pattern is passed as-is to grep
, or you get an error). So they must be quoted for the shell (with single quotes for instance as in the solutions here). For instance, if there's a file called r
in the current directory, and one called d
, grep [myword]
would become grep d r
in all shells but fish
.
[...]
is also a special operator in regular expressions (very similar to the [...]
glob operator), grep '[myword]'
would match on lines that contain m
, y
, w
, o
, r
or d
. So you need to escape the opening [
for grep
(for regular expressions) as well. That can be done with grep '\[myword]'
or grep '[[]myword]'
.
^
is another regular expression operator that means: match at the beginning of the line only. So grep '^\[myword]: '
matches on lines that start with [myword]:
.
While grep
is just meant to print matching lines (is not otherwise a stream editor like sed
is), GNU grep
added the non-standard -o
option for it to print the matching portion(s) of the line (if non-empty). It also added the -P
options to use perl compatible regular expressions (in PCRE) instead of basic ones without -P
.
In recent PCREs, \K
is an operator that resets the start of the matching portion. So in grep -Po '^\[one]: \K.*'
, we do print the matching portion because of -o
, but because of \K
, that matching portion becomes the sequence of characters (.*
) that is found after [one]:
.