awk question
Polytropon
freebsd at edvax.de
Mon Oct 5 02:30:10 UTC 2015
On Sun, 4 Oct 2015 19:55:08 -0453.75, William A. Mahaffey III wrote:
> I am using awk & smartctl in a small shell script to print out HDD temps
> in a purty format, 1 line per drive. As it happens, the output I want is
> spread out over 4 lines of smartctl out, requiring (I *think*) 4 calls
> to smartctl each piped to its own awk invocation to pull out the line I
> want & print its info out. Is there some way to get awk to consider more
> than 1 line at a time ? In my case my 4 lines are indeed sequential, &
> it would be a bit more efficient if I could process all 4 lines once I
> found the 1st one. This is definitely *not* critical, what I have now
> works AOK, I was/am just curious if it could be optimized a bit. TIA &
> have a good one.
I'm not sure I understand your question correctly, as you're not
providing some example input data and what output you want. But
awk can process one line against multiple patterns, and if, let's
say, 4 patterns match, 4 lines will be output:
smartctl <params> | awk '
/pattern1/
/pattern2/
/pattern3/
/pattern4/
' > out.txt
If no action is provided, the whole line will be printed; if you
just want some (maybe postprocessed) fields of a line, add
{ print <whatever }
to each pattern. Another way is "counting down" the amount of
additional lines after one pattern has been found:
smartctl <params> | awk '
{
if (nextlines > 0) {
print;
nextlines--;
}
}
/pattern/ {
nextlines = 4;
}
' > out.txt
The first block without a pattern will always be executed
(in this case, "print" is the command that will be called
for all desired lines), and the one with a pattern that
will "trigger" that first block to actually output something.
By the way: If there is no processing, and you just need some
data lines as is, why not use grep?
smartctl <params> | grep "<pattern>" -A 4 > out.txt
See "man grep" for details on the -A option.
--
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...
More information about the freebsd-questions
mailing list