why this code is not working?
#! /bin/ksh
awk -F':' '{
if( match($0,":ser开发者_StackOverflowver:APBS") )
{
print x;
x=$0;
}
}' iws_config4.dat
You write your program in native awk
as:
awk -F':' '/:server:APBS/ { print x; x=$0; }' iws_config4.dat
An awk
program consists of patterns and the actions to take when those patterns match. What you wrote is tantamount to abusing the built-in facilities of awk
.
Given that you're only interested in $0
, the field separator is redundant, so the -F':'
argument could go.
What your program does is:
- read a line.
- if it matches the pattern
- print the last line that matched
- save the current line
So, if your input contains one match, you see nothing output (or, more precisely, a blank line). If your input contains two matches, you see the first; if three, the first two; and so on.
Given the desire to emulate 'grep -B1 :server:APBS iws_config4.dat
', you can do:
awk '/:server:APBS/ { print old }
{ old = $0 }' iws_config4.dat
If the line matches, print the old saved line. Regardless, store the current line as the (new) old saved line.
It probably can all be flattened onto one line. It is crucial that the pattern match precede the unconditional save.
Given the script k.awk
and data file iws_config4.dat
shown, I get the output I expect. What do you get? What do you expect?
$ cat iws_config4.dat
One line of text followed by the marker
:server:APBS blah blah bah 1
:server:APBS blah blah bah 2
More text
Blah blah blah
$ cat k.awk
awk '/:server:APBS/ { print old }
{ old = $0 }' iws_config4.dat
$ sh k.awk
One line of text followed by the marker
:server:APBS blah blah bah 1
$
If blank lines could be the trouble, only save non-blank lines:
awk '/:server:APBS/ { print old }
/[^ ]/ { old = $0 }' iws_config4.dat
The second line now is only active on lines that contain at least one non-blank character, so only those lines will be saved.
精彩评论