Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

grep and pull number of lines above...

Status
Not open for further replies.

ryanc2

MIS
Apr 18, 2003
73
US
I need to pull the 2 lines before a string of "^" charactors.

For example:

Date
Version
^^^^^^^^^^^^^^^^^^^

Is it possible to grep for the ^ and retrieve the previous 2 lines?

Thanks in advance.
 
Well if you have GNU grep, then you can use this option
Code:
`-B NUM'
`--before-context=NUM'
     Print NUM lines of leading context before matching lines.
 
I'm working in SCO UNIX. I found that option searching some other forums, but it won't work for me.
 
Well you can do it with an AWK script
Code:
#!/bin/awk -f
# find the match
/^\^/ {
  print l1
  print l2
}

# record the previous two lines
{
    l1 = l2
    l2 = $0
}
# end

Save this as say 'myscript' (choose your own name), then type this command line
Code:
awk -f myscript file.txt
file.txt is the file you want to search
 
Or just...

awk '/^\^/ {print a[(NR-2)%2] "\n" a[(NR-1)%2]} {a[NR%2]=$0}' file.txt


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top