开发者

unix extract multiple lines

开发者 https://www.devze.com 2023-04-03 02:13 出处:网络
I have the following file: $cat somefile Line1 T:10 Hello Var1 = value1 Var2 = value2 Line2 T:2 Where VarX1 = ValueX1

I have the following file:

$cat somefile
Line1 T:10 Hello
   Var1 = value1
   Var2 = value2

Line2 T:2 Where
   VarX1 = ValueX1
   VarX2 = ValueX2

Line3 T:10 AAAA
   Var10 = Val1
   Var11 = Val11

Line4 T:10 ABCC
   Var101 = Val110

... What I need is by giving the search criteria, 开发者_JAVA技巧it should get multiple lines. For example, if the search criteria is -- T:10 -- then it should give

Line1 T:10 Hello
   Var1 = value1
   Var2 = value2

Line3 T:10 AAAA
   Var10 = Val1
   Var11 = Val11

I tried the sed command

sed -ne '/T:10/,/^$/p' somefile

But this is not working properly, it is getting other lines too sometimes. Is there anything that I am doing wrong here?


This is a "paragraph" grep. Linux/GNU grep doesn't have a paragraph mode and I haven't done it in sed, but you can use perl.

perl -00 -ne 'print if /T:10/' somefile


Here's a bash solution

#!/bin/bash

data=$(<file)
search="T:10"
OLDIFS="$IFS"
IFS="|"
data=(${data//$'\n\n'/|})
for i in "${!data[@]}"
do
    case "${data[$i]}" in
     *"${search}"* ) echo "$i : ${data[$i]}" ;;
    esac
done
IFS="$OLDIFS"


This might work for you (GNU sed):

sed -n '/T:10/{:a;N;/^$/M!ba;p}' file

Turn off automatic printing by using the -n option. Gather up lines between T:10 and an empty line and print them otherwise do not.

0

精彩评论

暂无评论...
验证码 换一张
取 消