If I take your question literally
(and don’t limit myself to trying to build on your incomplete answer)
I believe that the correct answer is:
egrep '^\s*(unsigned\s+)?int\s+[_A-Za-z][_A-Za-z0-9]*\s*;\s*(//.*)?$' myfile.txt
Step by step:
^ to anchor the search to the beginning of the line.
\s* to allow any number of whitespace characters (space or tab)
to occur at the beginning of the line, before the declaration.
(unsigned\s+)? to allow “unsigned” to appear zero or one time.
- If it is present, it is followed by one or more spaces —
int\s+ matches the “int” keyword, also followed by one or more spaces.
[_A-Za-z] — the first character of a C variable name
must be a letter or an underscore (
[_A-Za-z0-9]* — subsequent characters of a C variable name
may be letters, underscores, or digits.
There may be any number of them (including zero,
since we’re talking about what follows the first character).
- (Some C compilers probably impose a maximum identifier length.
I don’t remember whether the Standard does,
and I’m not going to bother looking it up.)
\s* to allow any number of spaces …
- … before the
\s* to allow any number of spaces after the semicolon.
(//.*)? — optionally allow a
// comment, and
$ to anchor the search to the end of the line.
If you want, you can
- If you’re typing this at the keyboard,
you may need to type Ctrk+V and then Tab
in order to get an actual tab character in the command line.
(Of course this won’t be an issue if you’re writing a script.)
egrep '^(unsigned )?int [^=]*;' myfile.txt
command, shown in another answer, prints the following lines:
int a, b; // Multiple variables declared.
int c; int d; // Multiple “int” declarations.
int e; float f; // Multiple declarations where only the first is an “int”.
int g; // Array.
int *h; // Pointer.
int func(); // Function.
int 3D; // Illegal variable name.
int 42; // Not even an illegal variable name.
(which it should not print), and skips the following lines:
int s; // Space(s) at the beginning of the line.
int t; // Tab after “int”.
unsigned int u; // Multiple spaces after “unsigned”.
unsigned int v; // Tab after “unsigned”.
(which it should print).