Bash regex match line number determination

Determining Line Number of Bash Regex Matched Lines

In Linux Bash language command line, there are cases when you want to know which line number a regex match is on.

Shou Arisaka
1 min read
Nov 25, 2025

In Linux Bash language command line, there are cases when you want to know which line number a regex match is on.

ag hogehoge links.txt | ag --only-matching "^\d+"

# or 

grep -Fn hogehoge links.txt | sed -Ee 's/^([0-9]+).*/\1/g'

ag is simpler, but ag can’t be manually installed, so it may not be available on rental servers. In that respect, grep can be used even on servers like Xserver. It’s a matter of choosing the right tool.

bash - How to get the line number of a match? - Stack Overflow

Share this article

Shou Arisaka Nov 25, 2025

🔗 Copy Links