Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep for a line containing at most one forward slash?

Tags:

regex

grep

I'm trying to get the size of the top level directories under the current directory (on Solaris). So I'm piping du to grep and want to match only those lines that have a single forward slash ie. the top level directories.

Something like:

du -h | grep -e <your answer here>

but nothing I try works. Help appreciated!

like image 863
David Avatar asked Aug 28 '10 12:08

David


People also ask

How do you grep a string with a forward slash?

The forward slash is not a special character in grep, but may be in tools like sed, Ruby, or Perl. You probably want to escape your literal periods, though, and it does no harm to escape the slash. This should work in all cases: \.

How do you grep for lines that don't match?

To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters). By default, grep is case-sensitive.

How do you grep 3 lines after a match?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.

How do you grep with additional lines?

To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.


1 Answers

grep -e '^[^/]*/[^/]*$'

Note that this matches lines that have exactly one (not at most one) slash, but that should be OK for your usage.

You could also probably do something with the -s switch

du -hs */
like image 70
Matti Virkkunen Avatar answered Nov 13 '22 11:11

Matti Virkkunen