Shell 获取指定行的内容

时间:2023-03-09 05:53:32
Shell 获取指定行的内容

需求: 有一个文件,根据指定的字符串,得到该字符串上两行的内容。

文件内容如下:

 linux-56:# cat sys.ttconnect.ini
# Copyright (C) 1999, 2006, Oracle. All rights reserved. ###############################################################
# This is a file used for the TimesTen Client.
# It contains entries for each server.
# GMPC connects TimesTen server over TCP.
############################################################### [LocalHost_mpc1]
Description=First TimesTen Server
Network_Address=localhost
TCP_PORT=17002
TTC_Timeout=300 [LocalHost_mpc1_1]
Description=First TimesTen Server
Network_Address=linux-56
TCP_PORT=17002
TTC_Timeout=300

根据hostname 得到 [LocalHost_ 后面的用户名。

具体代码:

 #!/bin/sh
TT_DSN=`awk '/^setenv TT_DSN/ {print $3}' /export/home/oracle/.login | tail -`
#echo $TT_DSN
HOST_NAME=`hostname` TT_CONNECT_FILE=/opt/TimesTen/${TT_DSN}/info/sys.ttconnect.ini
start_line=`grep "Network_Address=$HOST_NAME" $TT_CONNECT_FILE -n | awk -F: '{print $1}'`
if [ "X" == "X$start_line" ]; then
start_line=`grep "Network_Address=localhost" $TT_CONNECT_FILE -n | awk -F: '{print $1}'`
fi #echo $start_line
check_line=$[$start_line - ]
#echo $check_line
DSN_TMP=`head -n $check_line $TT_CONNECT_FILE |tail -n +$check_line`
#echo $DSN_TMP DSN=`echo ${DSN_TMP:}`
DSN=`echo ${DSN%]}` #echo $DSN Result=`su - oracle -c "ttIsqlCS -connstr $DSN -v 1 -e 'call ttrepstateget;bye'"`
#echo $Result if [[ "*ACTIVE*" != $Result ]]; then
echo "not ACTIVE"
exit
else
echo "ACTIVE"
fi

这里主要可以学习的几个点在于:

1、如何根据指定的字符串,得到当前行的行号

2、根据行号获取该行附近的内容

3、字符串的截取

4、判断一个字符串是否包含指定的子字符串