user9062604
user9062604

Reputation:

Extract exact matching strings using 'grep'

I try to extract files with extension .mkv from mkv.md with grep

    $ grep -i 'mkv' mkv.md
    ./Volumes/Transcend/Downloads/The.Adventure.of.English.Ep4.mkv
    ./Volumes/Transcend/Downloads/The.Adventure.of.English.Ep5.mkv
    ./Volumes/Transcend/Downloads/The.Adventure.of.English.Ep6.mkv
    ...

There's a leading period in the output which should be removed manually. the result I desire is (without period symbol)

    /Volumes/Transcend/Downloads/The.Adventure.of.English.Ep4.mkv
    /Volumes/Transcend/Downloads/The.Adventure.of.English.Ep5.mkv
    /Volumes/Transcend/Downloads/The.Adventure.of.English.Ep6.mkv

I tried and get the same result.

    grep -i '\/.*\.mkv' mkv.md
    ./Volumes/Transcend/Downloads/The.Adventure.of.English.Ep4.mkv
    ./Volumes/Transcend/Downloads/The.Adventure.of.English.Ep5.mkv
    ./Volumes/Transcend/Downloads/The.Adventure.of.English.Ep6.mkv
    ...

How to solve the problem?

Upvotes: 0

Views: 71

Answers (3)

Wizard
Wizard

Reputation: 22153

You can use -o
-o, --only-matching :Prints only the matching part of the lines.

In your example:

grep -io '\/.*\.mkv' mkv.md
#please note that you can combine multiple options as the above, or
grep -i -o '\/.*\.mkv' mkv.md

Upvotes: 0

Maciej Białorucki
Maciej Białorucki

Reputation: 561

You can use cut :

cut -c 2- - cuts from second character to end of the string

In you example :

grep -i 'mkv' mkv.md | cut -c 2-

More examples here : https://en.wikipedia.org/wiki/Cut_(Unix)

Upvotes: 0

user9549915
user9549915

Reputation:

If you can use other commands, cut can help:

$ grep -i mkv mkv.md | cut -c 2-
/Volumes/Transcend/Downloads/The.Adventure.of.English.Ep4.mkv
/Volumes/Transcend/Downloads/The.Adventure.of.English.Ep5.mkv
/Volumes/Transcend/Downloads/The.Adventure.of.English.Ep6.mkv

Upvotes: 1

Related Questions