1830207 Members
1845 Online
109999 Solutions
New Discussion

Using awk and sed

 
SOLVED
Go to solution
SAM_24
Frequent Advisor

Using awk and sed

Hi,

Using either awk and sed I want to acheive this:

When I search for line 2 I want to print line1

line1
line2

How to do it?

Using GNU grep I can acheive it. But I want to use either sed or awk or both.

Thanks.
Never quit
4 REPLIES 4
Leif Halvarsson_2
Honored Contributor

Re: Using awk and sed

Hi
I am not sure I understand exact what you want to do but in general awk will be a good tool for such job. Here is a example, perhaps this can give you an idea. The example is from the "real world" but I have simplified it here.

I have a file with a long list of information about backup tapes and want the media id of all tapes which is not protected. The second field of the first line contains the id and the second fild of the second line protected or not.

The file:

Mediumidentifier 0901:3cf68aa3:55a6:0001
Protected Permanent

Mediumidentifier 0901:3cf68aa3:55a6:0002
Protected None



The awk script:

$1 == "Mediumidentifier" { IDE = $2}
$1 == "Protected" { if ($2 == "None") print IDE }

The script reads the file, line for line, if the first field is "Mediumidentifier" it load the variable IDE whith the second field of this line.
When it reads the next line and find the first field is "Protected" it check the second fild for "None". If so it print out the variable IDE.
As "Mediumidentifier" appers in the file before "Protected" the id of the not protected medium will pe printed.

Hope this can help you.


James R. Ferguson
Acclaimed Contributor
Solution

Re: Using awk and sed

Hi Raj:

# awk '{if ($2~/JKL/) {print X;B=1} else X=$0;B=0};END {if (B==1) print X}' /tmp/input

Given /tmp/input like:

1 ABC
2 DEF
3 GHI
4 JKL
5 MNO
6 PQR
7 STU

...will print

3 GHI

Regards!

...JRF...
H.Merijn Brand (procura
Honored Contributor

Re: Using awk and sed

perl -ne '/line2/&&print $p,$_;$p=$_' infile
Enjoy, Have FUN! H.Merijn
Fred Martin_1
Valued Contributor

Re: Using awk and sed

This is how I usually do that, with awk:

awk '
BEGIN{last="null"}
/searchstr/{print last}
last=$0
' filename

searchstr = the search string
filename = the file you're working on

Basically it just copies each new line into the variable "last" ... so if you find a match for searchstr, "last" holds the last line that was read.

The BEGIN statement pre-loads the "last" variable in case you get a match for searchstr on the very first line.

Fred
fmartin@applicatorssales.com