I am working on making a git command I use more useful. A common task I do is to grep my git rev-list --all. I wrote (aka cut and pasted another StackExchange answer) git command to do this for me.


function _search() {
    git rev-list --all | (
        while read revision; do
            git grep -F $1 $revision
_search $1

The output from this looks like:

f26ce56cf6b17401292c494f906b2b6a9071ca75:filename.py:grepped string

I usually take these results and run git show along with the commit and file path to see that particular version of the file. git show takes the input of {COMMIT HASH}:path/to/file.

What I'd ideally like is to have my git function stick a whitespace where the second : is, which would allow me more easily copy and paste the output of git-search into git show, ie:

f26ce56cf6b17401292c494f906b2b6a9071ca75:filename.py grepped string

I'd like to use BASH for this as I am already using BASH. My initial solution was to use Python but that seems needless to me. I just am not sure how best to achieve this in BASH.

1 Answer 1

sed 's/:/ /2'

This would change the second : character to a space.

You could stick that in as an extra stage of your function's pipeline:


git rev-list --all |
while read revision; do
    git grep -F "$1" "$revision"
done |
sed 's/:/ /2'

(I actually deleted the function as it didn't seem to be needed; note also the quoting of the variable expansions; oh, and it's a /bin/sh script since it's not using any bash-specific features (neither did yours, except for the unneeded function keyword))

  • That's perfect! And thanks for the other improvements as well. I wasn't aware sed could do this. Does that mean I can swap out the 2 for a 3 to remove the third instance? I only knew about d, e, and g. Guess I have a lot of sed to learn still. Aug 18, 2019 at 20:14
  • @IanPringle Yes, you can swap out the 2 for 3 or any other positive integer. There is no d flag to the s command in sed (not even in GNU sed). I assume that you're thinking about the d commad in sed.
    – Kusalananda
    Aug 18, 2019 at 20:17
  • @kusalanada That's great! Yes, I guess that's true the d replaces the s. Thanks again! Aug 18, 2019 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.