0

I'm trying to grep for a instance "test" in /etc/oratab. But wanted to display only the line that doesn't begin with a comment. Below are the lines from /etc/oratab file:

#test:/u01/appl/oracle/test/db/tech_st/12.1.0.2:N
test:/b001/app/oracle/testrac/db/tech_st/12.1.0.2:N         # line added by Agent

This is how I'm trying to get the details I'm interested in (placed the below in a shell script:

DB_NAME=test
env_var=`cat /etc/oratab |grep $DB_NAME |grep -v '#' |cut -d":" -f 2`
echo $env_var

The problem here is, as the 2nd line also has a comment at its end, it is also being ignored.

Please help.

Regards, RA

4 Answers4

2

awk would be a better choice here:

DB_NAME=test; export DB_NAME
file=$(awk -F: '$1 == ENVIRON["DB_NAME"] {print $2; exit}' < /etc/oratab)

printf '%s\n' "$file"

On Solaris, make sure to do:

PATH=$(getconf PATH):$PATH

(and use #! /usr/xpg4/bin/sh - if on Solaris 10 and older) to have standard utilities. Or use command -p awk. Otherwise, you may get an antiquated awk from the 70s.

1

A much simpler solution than re-writing it to use awk would be to add a simple ^ to indicate the start of a line:

env_var=`cat /etc/oratab |grep $DB_NAME |grep -v '^#' |cut -d":" -f 2`

The grep -v '^#' removes all lines starting with a # and is often useful.

Mikael Kjær
  • 1,001
0

With sed, you can combine both greps and the cut in one pass:

sed "/^$DB_NAME:/! d;s///;s/:.*//" /etc/oratab

With

  • /^$DB_NAME:/ selects all lines starting with $DB_NAME followed by :; the ! inverts the match, so the following d deleted all lines that don't match this pattern
  • s/// removes the last match, in this case the test:
  • s/:.*// removes the : and everything following
Philippos
  • 13,453
0

The other answers work for the example (file is CSV* (colon-separated values), searched-for string will be the first field, desired output is the second field), but none of these constraints / conditions is actually stated in the question.  And, while the question asks for a command that excludes lines that begin with a comment, that’s probably not what the OP really wants.  (What about a line like unwanted line:blah:blah #test, which contains test in a comment?)  The answer that the OP wants is

grep '^[^#]*test' /etc/oratab

or

grep "^[^#]*$DBNAME" /etc/oratab

which searches for a line where test appears, and all the characters before it are something other than #.

As usual, you should always quote your shell variable references (e.g., "$DB_NAME" and "$env_var") unless you have a good reason not to, and you’re sure you know what you’re doing.  And, as Stéphane Chazelas points out, if $DBNAME looks like a non-trivial regular expression (e.g., it contains ., * or []), there are likely to be unwanted results.