awk question

Hi experts,

Is it possiable to use awk print the line before one line 2 line for example

1111
2222
3333
4444
5555

I want to print the line bofore the line "5555" 2 line, the result should be 3333 something like grep -A (but not exactly the same, becasue grep -A 2 will print 3333 4444)

Try:

awk '/555/{print A[(NR-2)%3]}{A[NR%3]=$0}' infile

more general:

awk '/555/{print A[(NR-c)%(c+1)]}{A[NR%(c+1)]=$0}' c=2 infile

can you explain to me?I plan to buy one awk book, which one you recommand?:slight_smile:

Lei

Why not

grep -B2 5555 | head -1

(-B, not -A)

---

And yes, this is a GNU grep extension (thanks, Corona688).

Yet another way with ex...

ex +'/5555/-2 | q!' file

I think that's a GNU extension not found on most non-linux systems...

1 Like

I get an empty line...

That is strange...what OS and system are you on.

I tried it on Ubuntu and OSX...

I dont have Ubuntu but the ex command works on my hpux aix solaris and rhel boxes so frankly im at a loss...:confused:

Both OSX and Ubuntu offer vim instead of vi, so that is probably where the difference comes from. I just tried it on RHEL5.8 (or rather CentOS 5.8) and it does not work there either...

I thought I can get it from

awk '/5555/{print $(NR-2)}'

but it don't get the results, what's wrong with me

That is possible only if you save the lines as they are read in an array and at the end you print out the 2nd last item...

Something to keep in mind when choosing how to pass commands to ex: When ex (and ed) are reading commands from standard input, they abort with a meaningful exit status at the first sign of trouble. However, with ex, when commands are given as an option-argument (ed doesn't support this), if there's an error, ex will prompt for another command and wait. In this case, for example, if there was no line matching /5555/ , ex would not quit. Usually (but not always), this is not ideal.

Also, the output of that command depends on local settings. It may or may not print a line number. If the output is to be processed by a script, this adds unnecessary complexity (either settings need to be overridden or something downstream needs to handle both possible formats).

In my opinion, the simplicity of ed would be an asset for this task.

Using an old debian where ex is ViM 7.0, I see the desired line prepended by its line number. The mystery deepens. :slight_smile:

Perhaps it's related to your ex/vi rc file. What if you use /5555/-2p ?

Regards,
Alister

I had already tried 2p but, it returned the same output... I had also noticed that if I then also leave out | :q! I get the correct result in the editor, but when combined with the quit it leaves the editor but no output is shown..

--
vim 7.3, my .exrc file is empty ...

Greetings..

S.