Git grep across all new and modified files (before

2019-08-23 18:31发布

问题:

What command can I run in my Windows Git Bash that will show me the file names, line preview (context), and line numbers of all of the places there is "TODO" written in my code, limited to new files and modified files?

Inadequate Approach 1 (from here)

This is clunky and doesn't print line number:

function __greptodo {
    QUERY="TODO"
    for FILE in `git diff --name-only`; do
        grep "$QUERY" $FILE 2>&1 >/dev/null
        if [ $? -eq 0 ]; then
            echo '———————————————'
            echo $FILE 'contains' $QUERY
            grep "$QUERY" $FILE 2>&1
        fi
    done
}
alias greptodo=__greptodo

Inadequate Approach 2 (from here)

This is much better (shows context and includes new files and modified files) but still doesn't print line numbers:

grep -s "TODO" $(git ls-files -m)

回答1:

The -n flag tells grep to show the line number, so you were close. Try:

grep -sn "TODO" $(git ls-files -m)

To include untracked files, use the --others (-o) flag, and the --exclude-standard flag to exclude the files usually ignored by Git:

grep -sn "TODO" $(git ls-files -mo --exclude-standard)


标签: git grep diff