Views:
325,679β
Votes: 3β
Tags:
bash
grep
iconic
Link:
π See Original Answer on Stack Overflow β§ π
URL:
https://stackoverflow.com/q/62724650
Title:
Grep characters before and after match?
ID:
/2020/07/04/Grep-characters-before-and-after-match_
Created:
July 4, 2020
Edited: September 4, 2021
Upload:
October 19, 2025
Layout: post
TOC:
false
Navigation: false
Copy to clipboard: false
Iβll never easily remember these cryptic command modifiers so I took the top answer and turned it into a function in my ~/.bashrc file:
cgrep() {
# For files that are arrays 10's of thousands of characters print.
# Use cpgrep to print 30 characters before and after search pattern.
if [ $# -eq 2 ] ; then
# Format was 'cgrep "search string" /path/to/filename'
grep -o -P ".{0,30}$1.{0,30}" "$2"
else
# Format was 'cat /path/to/filename | cgrep "search string"
grep -o -P ".{0,30}$1.{0,30}"
fi
} # cgrep()
Hereβs what it looks like in action:
$ ll /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
-rw-r--r-- 1 rick rick 25780 Jul 3 19:05 /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
$ cat /tmp/rick/scp.Mf7UdS/Mf7UdS.Source | cgrep "Link to iconic"
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
$ cgrep "Link to iconic" /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
The file in question is one continuous 25K line and it is hopeless to find what you are looking for using regular grep.
Notice the two different ways you can call cgrep that parallels grep method.
There is a βniftierβ way of creating the function where β$2β is only passed when set which would save 4 lines of code. I donβt have it handy though. Something like ${parm2} $parm2. If I find it Iβll revise the function and this answer.