1

How does one grep/search a text file so that the results show the first line with the string, and then every other line until the last line with the string?

So, if I have a file that looks like this:
A
A
B
C
C
B
A
A

And I perform this command searching for "B", it would yield:
B
C
C
B

IVR Avenger
  • 325
  • 1
  • 5
  • 16

3 Answers3

0

I would use sed :

sed -n '/B/,/B/p' file
Shan-x
  • 168
  • 2
  • 9
0

It is not a commandline but a small function which can help you (bash on Linux):

 function grepbetween {
    match=$(grep -n "$1" "$2" | sed -e 's/:.*//')
    nolines=$(echo $match | wc -w)
    if [ $nolines -gt 1 ]
        then
            init=$(echo $match | cut -f1 -d" ")
            end=$(echo $match|cut -f${nolines} -d" ")
            nolines=$(wc -l "$2" | awk '{print $1}')
            startline=$((nolines-init))
            betweenlines=$((end-init))
            cat $2 | tail -${startline} | head -${betweenlines}
        fi
    }

An an example of its output:

[jbuser@jbossserver configuration]$ grepbetween extensions standalone.xml
        <extension module="org.jboss.as.clustering.infinispan"/>
        <extension module="org.jboss.as.connector"/>
        <extension module="org.jboss.as.deployment-scanner"/>
        <extension module="org.jboss.as.ee"/>
        <extension module="org.jboss.as.ejb3"/>
        <extension module="org.jboss.as.jaxrs"/>
        <extension module="org.jboss.as.jdr"/>
        <extension module="org.jboss.as.jmx"/>
        <extension module="org.jboss.as.jpa"/>
        <extension module="org.jboss.as.jsf"/>
        <extension module="org.jboss.as.logging"/>
        <extension module="org.jboss.as.mail"/>
        <extension module="org.jboss.as.naming"/>
        <extension module="org.jboss.as.pojo"/>
        <extension module="org.jboss.as.remoting"/>
        <extension module="org.jboss.as.sar"/>
        <extension module="org.jboss.as.security"/>
        <extension module="org.jboss.as.threads"/>
        <extension module="org.jboss.as.transactions"/>
        <extension module="org.jboss.as.web"/>
        <extension module="org.jboss.as.webservices"/>
        <extension module="org.jboss.as.weld"/>
    </extensions>
alphamikevictor
  • 1,062
  • 6
  • 19
0

yet another alternative to prove Unix has more ways than one to skin a cat ;) (made into multiline for readability, but could be converted back into one-liner):

$ FILE=/etc/passwd
$ SEARCH4=daemon 
$ tail -n +$(grep -i $SEARCH4 -m 1 -n $FILE | cut -d: -f1) $FILE
Droopy4096
  • 680
  • 4
  • 8