Skip to content
shellhacks.dev
Text Processing

Search for a Tab Character with grep in Bash

Search for a literal tab with a Bash ANSI-C quoted string or with grep -P. A plain backslash-t pattern matches the letter t in GNU grep 3.8.

1 min read
Summarize in AI

You need the lines that contain a tab, such as the columns of a tab-separated file.

Shell
printf 'a\tb\ntest\n' > t.txt
grep $'\t' t.txt | cat -A
grep -P '\t' t.txt | cat -A
grep '\t' t.txt
Text
a^Ib$
a^Ib$
test

In Bash, ANSI-C quoting (a dollar sign before single quotes) turns the tab escape into a real tab character before grep sees it. grep -P understands the escape itself, and both matched the first line, which cat -A shows as a^Ib$. A plain single-quoted tab escape is different: GNU grep reads it as the letter t, so the third command matched the line test and skipped the tab line. See ANSI-C Quoting and the grep manual for -P.

-P is a GNU extension and is missing from the grep on macOS and BusyBox, and ANSI-C quoting is not POSIX, so in sh put the tab in a variable with printf first. At an interactive prompt, Ctrl-V followed by Tab also inserts a literal tab.

Taggedgreptext
Share

More snippets

Text Processing

Replace Only the Nth Match on a Line with sed

Replace only the second or a later match on a line with a numeric flag on the s command, and add g to replace from that match onward. The count restarts on every line.

1 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.