awk get matched line's previous line

hi everyone,

a
b in
c
d
e
f in
g

output is:

a
e

so awk search for "in", then print out the matched line's previuos line.
Please advice.
Thanks

try this,

awk '/in/ { print a } { a = $0}' inputfile
2 Likes

Thanks

Nice with awk.
Can anyone do the same thing with sed?

Something like this?

sed -n 'N;/in/s/\n.*//p' 

No,
I got the output:

b in
e

Works fine on my HP-UX system, try <Ctrl-v><Enter> instead of \n:

sed -n 'N;/in/s/^M.*//p'
1 Like

What does the capital "N" do?

---------- Post updated at 04:54 PM ---------- Previous update was at 04:42 PM ----------

@Franklin,
If this is the input file:

c
a
b in
d
e
f in
g

Now run your sed command.

Ok, that was just "freehand" command...:smiley: try it with:

sed -n -e '/in/ !{x;d;}' -e '/in/{x;p;x;}' file

or with this approach:

sed -n -e '/in/ !{h;}' -e '/in/ {H;x;s/\n.*//p;}' file

Could you please explain each command option?
I did man sed but it's not quite clear to me.

Ok, here we go, the first one:

sed -n -e '/in/ !{x;d;}' -e '/in/{x;p;x;}' file
/in/ !{x;d;}	# Line doesn't contain "in", exchange the pattern space with the hold buffer 
		# and delete the pattern space

/in/{x;p;x;}	# Line contains "in", exchange the pattern space with the hold buffer,
		# print the pattern space and exchange the pattern space with the hold buffer

The second approach:

sed -n -e '/in/ !{h;}' -e '/in/ {H;x;s/\n.*//p;}' file
/in/ !{h;}		# Line doesn't contain "in", copy the pattern buffer into the hold buffer

/in/ {H;x;s/\n.*//p;}	# Line contains "in", append the pattern space to the buffer, with a "\n" between the lines,
			# exchange the pattern space with the hold buffer, remove the last line and print the line

If this is abracadabra to you, you can have a read of a sed tutorial:

Sed - An Introduction and Tutorial

Regards

1 Like

Thanks for your explanation.
Both commands are practical and easy.