Printing out integer literals occurrences on unix

2019-09-21 08:54发布

问题:

I"m trying to use the grep command to print out all occurrences of integer literals in a foo.txt file, but I can't seem to find a way how.

The only thing I can think of for this is using [0-9] as my pattern, but that prints all lines with occurrences of the number rather than just the literals.

EDIT: Say foo.txt contains:

string string1 = "Hello world";
cout << string1.at(2) << endl;
cout << string1at(3) << endl;

Then the expected output would be:

cout << string1.at(2) << endl;
cout << string1at(3) << endl;

回答1:

Some like this:

awk -F"[()]" '$2' foo.txt
cout << string1.at(2) << endl;
cout << string1at(3) << endl;

Or to make sure it contains numbers between parentheses:

awk -F"[()]" '$2~/[0-9]+/' file
cout << string1.at(2) << endl;
cout << string1at(3) << endl;


回答2:

Use grep -o [1-9][0-9]* foo.txt



回答3:

Here's another way using lookaround assertions:

Test string:

hello 1234 hello234h 122test 123

Regex:

grep -o "(?<=\s|^)([0-9]+)(?=\s|$)" foo.txt

Matches:

"1234", "123"

Regex example:

http://regex101.com/r/vP5zD7



标签: regex unix grep