Reputation: 16029
Like I have a text file with,
+
Code here
+
Code here +
Code+ here
+
Code here
And I want to grep this file and only show the line with a + character only? What regex should I construct?
Please advise
Many thanks
Upvotes: 0
Views: 220
Reputation: 881463
If you want a line with nothing but the +
character, use:
grep '^+$' inputFile
This uses the start and end markers to ensure it only has that one character.
However, if you want lines with only a +
character, possibly surrounded by spaces (as seems to be indicated by your title), you would use something like:
grep '^ *+ *$' inputFile
The sections are:
"^"
, start of line marker." *"
, zero or more spaces."+"
, your plus sign." *"
, zero or more spaces."$"
, end of line marker.The following transcript shows this in action:
pax> echo ' +
Code here
+
Code here +
Code+ here
+
Code here' | grep '^ *+ *$' | sed -e 's/^/OUTPUT:>/' -e 's/$/</'
OUTPUT:> +<
OUTPUT:> +<
OUTPUT:> + <
The input data has been slightly modified, and a sed
filter has been added, to show how it handles spacing on either side.
And if you want general white space rather than just spaces, you can change the space terms from the current " *"
into "\s*"
for example.
Upvotes: 1
Reputation: 56069
If I understand correctly, you want the line with only a +
, no whitespace. To do that,
use ^
and $
to match the beginning and end of the line, respectively.
grep '^+$' filename
Upvotes: 1