I use below command to filter the file for # and empty lines. But, how can we grep uncommented and blank lines in linux with single grep.
[root@localhost ~]# cat test | grep -v ^# | grep -v ^$
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.Sign up to join this community
For simple cases, my go-to pattern for this is:
$ egrep '^[^#]'
This pattern matches lines which begin with some character OTHER than a pound sign.
If you extend the definition of 'blank' line to include a line entirely of whitespace, then the pattern fails, as it will match such a line. The pattern also fails if you allow arbitrary whitespace before the pound sign in a comment line (as Apache, bash, and others do).
If those cases are important to you, this pattern is better:
$ egrep '^[[:blank:]]*[^[:blank:]#]'
$ cat test # comment # spaces then comment config # then comment before empty line after empty line space only on next line tab only on next line $ egrep '^[[:blank:]]*[^[:blank:]#]' test config # then comment before empty line after empty line space only on next line tab only on next line $
IIUC, you want to show non-blank and non-commented lines. You can do that with
-e using a single
grep -v -e "^#" -e "^$" test
For example, if your
test looks like this:
#a uncommented line #comment below blank line
output will be:
$ grep -v -e "^#" -e "^$" test uncommented line
consider the file:
valid config line 1 # Comment valid config line 2 # Comment Blank line between These two One space in the line between These two
If you consider the cases:
You can use
cat file | grep -v '^$\|^#' or
cat file | grep -v '^\($\|#\)'
And you will get something like:
valid config line 1 valid config line 2 # Comment Blank line between These two One space in the line between These two
However, I would consider also lines that start with a config line and then have an inline comment (supported in several config files), lines that are not blank but have only spaces, for this in a single command, I would use sed:
cat file | sed '/^\(#\|[[:space:]]*$\)/d;s/#.*//g'
valid config line 1 valid config line 2 Blank line between These two One space in the line between These two
[[:space:]]*$matches 0 or more spaces before the end of the line
^\(a\|b\)matches lines starting with
bwill match all lines starting with
#, blank lines, and lines that only have spaces.
/match/ddeletes all the matching lines
;separates sed commands
aand an empty
bwill remove all the matching comments after a line.
Hope it helps. Regards
[root@localhost ~]# cat file | grep -v ^'$\|#'