Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep lines for numbers greater than given number

Tags:

bash

shell

awk

I'm trying to grep for lines in the first field of an output that are greater than a given number. In this instance, that number is 755. Ultimately, what I'm doing is trying to list every file with privileges greater than (and not equal to) 755 by using stat -c '%a %n' * and then pipe to some grep'ing (or possibly sed'ing?) to obtain this final list. Any ideas how this could best be accomplished?

like image 566
user2150250 Avatar asked Apr 30 '13 22:04

user2150250


People also ask

Does grep work with numbers?

grep -r -L "[^0-9 ]" . [^0-9 ] will match anything that doesn't contain digits or spaces (thought that would be fitting or else all files that contain spaces and number would be discarded). The -L flag is --files-without-match , so this basically gives you files that DO contain digits or spaces.

How do you grep above and below?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.

How do you grep line numbers?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.

How do you grep multiple lines after a match?

Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the match!


2 Answers

try this:

stat -c '%a %n' *|awk '$1>755' 

if you just want the filename in your final output, skip the privilege numbers, you could:

stat -c '%a %n' *|awk '$1>755{print $2}' 

EDIT

actually you could do the chmod within awk. but you should make sure the user execute the awk line has the permission to change those files.

stat -c '%a %n' *|awk '$1>755{system("chmod 755 "$2)}' 

again, assume the filename has no spaces.

like image 54
Kent Avatar answered Sep 20 '22 09:09

Kent


I'd use awk(1):

stat -c '%a %n' * | awk '$1 > 755' 

The awk pattern matches lines where the first field is greater then 755. You could add an action if you want to print a subset of a line or something different, too (See @Kent's answer).

like image 29
Carl Norum Avatar answered Sep 19 '22 09:09

Carl Norum