The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

Views: 262,380β€…    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: November 24, 2022    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.

⇧ How to fix screen overlap and top left zoom of HD external monitors while using 4k primary Linux Ubuntu 20? Accidentally copied files to wrong directory  β‡©