Search code examples
gitgrepcutgit-diff

Git Diff and Grep a list of strings out


If I get a list of files that have changed how can I pull a certain string out and print it?

git diff --name-only origin/master

Output:

server/packages/sharing/src/test1.js
client/packages/sharing/src/test2.js
client/packages/foo/src/test3.js
client/packages/foo/src/test4.js
client/packages/bar/src/test5.js
client/packages/bar/src/test6.js
client/packages/baz/src/test7.js
client/packages/baz/src/test8.js

I would like to get the third word in the path when examining the file list.

Trying to get:

sharing, foo, bar, baz

or

sharing
foo
bar
baz

I tried git diff --name-only origin/master | grep -o '*/packages/*/src' but I'm not sure how to capture the word. (using zsh on a Mac if it helps with narrowing down what's on my system)


Solution

  • You can decompose your path with cut command :

    git diff --name-only origin/master | cut --delimiter / --fields 3
    

    On Mac, try :

    git diff --name-only origin/master | cut -d/ -f3