Skip to content
shellhacks.dev
Text Processing

Print the Byte Offset of Each grep Match

Print the byte offset of each match with grep -b -o. Without -o the offset is that of the start of the line, not of the match.

1 min read
Summarize in AI

You need the position of a match inside a file, for instance to cut it out with dd or head -c.

Shell
printf 'alpha beta\nbeta gamma beta\n' > t.txt
grep -b -o beta t.txt
echo ---
grep -b beta t.txt
Text
6:beta
11:beta
22:beta
---
0:alpha beta
11:beta gamma beta

-b prefixes each output line with its zero-based byte offset. Combined with -o, each match is printed on its own line and the offset is that of the match, so the first hit is at byte 6 and the third at byte 22. Alone, the number is the offset where the matching line starts. Both forms are in the GNU grep manual.

Offsets are in bytes, not characters, so a file with multibyte text gives numbers that differ from a character count. Offsets restart for each file when several are searched, and a binary file needs -a for the match to be reported at all. Pair the offset with tail -c +N or dd skip=N to extract from that position.

Taggedgreptext
Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.