KarthikSinghDBA
KarthikSinghDBA

Reputation: 3

Linux Grep or Awk to find strings and store into array

I would like to print the string in the following pattern. And I would like to store it in a array. Please help me, I need O/p as follows

test11
orcl

My commands/Tries

egrep -i ":Y|:N" /etc/oratab | cut -d":" -f1 | grep -v "\#" | grep -v "\*" | tr -d '\n' | sed 's/ /\n/g' | awk '{print $1}'

Above commands O/p:

test11orcl

Contents of Oratab will be as follows,

[oracle@rhel6112 scripts]$ cat/etc/oratab
#
# This file is used by ORACLE utilities.  It is created by root.sh
# and updated by the Database Configuration Assistant when creating
# a database.

# A colon, ':', is used as the field terminator.  A new line terminates
# the entry.  Lines beginning with a pound sign, '#', are comments.
#
# Entries are of the form:
#   $ORACLE_SID:$ORACLE_HOME:<N|Y>:
#
# Multiple entries with the same $ORACLE_SID are not allowed.
#
#  
test11:/u01/app/oracle/product/11.2.0/dbhome_1:N 
orcl:/u01/app/oracle/product/10.2.0/db_1:N

End of Cat Output

From the above file am trying to extract the STRING before the :/

Upvotes: 0

Views: 1425

Answers (2)

Fredrik Pihl
Fredrik Pihl

Reputation: 45672

As a start, try this:

$ cat input.txt
test11:/u01/app/oracle/product/11.2.0/dbhome_1:N
orcl:/u01/app/oracle/product/10.2.0/db_1:N

$ awk -F: '{print $1}' input.txt
test11
orcl

update

Using bash:

#!/bin/bash

ARRAY=()
while read -r line
do
    [[ "$line" = \#* ]] && continue
    data=$(awk -F: '{print $1}' <<< $line)
    ARRAY+=($data)
done < input.txt

for i in "${ARRAY[@]}"
do
    echo "$i"
done

In action:

$ ./db.sh 
test11
orcl

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174736

You could use sed also,

sed -r 's/^([^:]*):.*$/\1/g' file

Example:

$ cat cc
test11:/u01/app/oracle/product/11.2.0/dbhome_1:N
orcl:/u01/app/oracle/product/10.2.0/db_1:N
$ sed -r 's/^([^:]*):.*$/\1/g' cc
test11
orcl

OR

$ sed -nr 's/^(.*):\/.*$/\1/p' file
test11
orcl

Upvotes: 0

Related Questions