tiger_groove
tiger_groove

Reputation: 1016

Regex trying to match everything before backslash / not working

I am attempting to use regex to match everything before the /, but when i try the following I get nothing outputted. I double checked my regex and seems okay, but not sure why it isn't working..

[user@user my_dir]$ tar -tf abc_de123_01.02.03.4.tgz | grep -m1 /
abc_de123_01.02.03.4/abcde.ini
[user@user my_dir]$ tar -tf abc_de123_01.02.03.4.tgz | grep -m1 .*\/
[user@user my_dir]$ tar -tf abc_de123_01.02.03.4.tgz | grep -m1 /$

expected output:
abc_de123_01.02.03.4/

Upvotes: 0

Views: 396

Answers (2)

Jean Carlo Machado
Jean Carlo Machado

Reputation: 1618

Grep by default works on line wise operations. If you need only part of the string in all the lines you might use cut instead.

tar -tf abc_de123_01.02.03.4.tgz | cut -d'/' -f1 

Now if you need only the first part of the first match sed come in hand:

tar -tf abc_de123_01.02.03.4.tgz | sed "1q;d" | cut -d'/' -f1 

Upvotes: 0

ruakh
ruakh

Reputation: 183351

There are three problems here.

  • One problem is that * has a special meaning to your shell; if you run echo grep -m1 .*\/, you'll see that your shell is expanding .*\/ in a way you don't expect.

  • One problem is that grep prints matching lines by default. If you want it to print just the matching part of a line, you need the -o flag.

  • One problem that's not actually breaking your command, but that you should nonetheless fix, is that your shell uses \ as a quoting (escape) character, so \/ actually means just /. (The reason this doesn't break anything is that / isn't special to grep anyway, so you didn't actually need the \ for anything.)

So:

grep -m1 -o '.*/'

which finds the first line containing /, and prints everything up through the last / on that line.

Incidentally, / is not a backslash, but simply a slash (or sometimes forward slash). A backslash is \.

Upvotes: 2

Related Questions