Hot answers tagged

9 votes

What is the sed equivalent for "grep -o"?

Update to fix behaviour for zero-length regex matches: sed 't match;s/REGEX/\n&\n/g;D;:match;/^\n/!P;s/\n//;D' file Globally substitute matches with <newline><matched part><newline&...
user avatar
  • 2,553
7 votes
Accepted

Why do empty matching regexps work differently in sed and grep?

grep -o is documented in grep --help as -o, --only-matching show only nonempty parts of lines that match and in the manual as Print only the matched (non-empty) parts of matching lines, with ...
user avatar
6 votes

What is the sed equivalent for "grep -o"?

This is very similar to rowboat’s answer (but developed independently), and with maybe slightly more verbose explanation. Using GNU sed: sed -En 't dummy; : dummy; s/[a-zA-Z]{3}[0-9]{4}/&\n/; T; s/...
user avatar
4 votes

Why do empty matching regexps work differently in sed and grep?

The behavior of 0-length string matches can be special cased in the code, or not. For instance the sed but not perl $ echo aabb | sed 's/a*/X/g' XbXbX $ echo aabb | gsed 's/a*/X/g' XbXbX $ echo aabb | ...
user avatar
  • 31.6k
3 votes

What is the sed equivalent for "grep -o"?

Only with GNU sed , three ways can be: sed -En ' s/[a-zA-Z]{3}[0-9]{4}/\n&\n/g s/.*\n(.*\n)/\1/Mg s/(.*)\n.*/\1/p ' file # or without -n sed -E ' s/[a-zA-Z]{3}[0-9]{4}/\n&\n/ s/.*\n/...
user avatar
  • 5,546
2 votes
Accepted

grep exit with status 1 when found zero value

You don't say which shell this is being written for, but generally variable names can't start with a digit. I would strongly recommend that you start to paste your code into https://shellcheck.net (or ...
user avatar
  • 91.8k
1 vote

Why do empty matching regexps work differently in sed and grep?

$ echo 'Hello' | grep -o 'N*' $ echo $? 0 It does match an empty substring of that input line, as shown by the exit status. (With a different pattern like N, we still get nothing on stdout, but an ...
user avatar
  • 6,203

Only top scored, non community-wiki answers of a minimum length are eligible