Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 5 Oct 2015 04:21:29 +0200
From:      Polytropon <freebsd@edvax.de>
To:        "William A. Mahaffey III" <wam@hiwaay.net>
Cc:        FreeBSD Questions !!!! <freebsd-questions@freebsd.org>
Subject:   Re: awk question
Message-ID:  <20151005042129.1f153ec6.freebsd@edvax.de>
In-Reply-To: <5611C922.4050007@hiwaay.net>
References:  <5611C922.4050007@hiwaay.net>

next in thread | previous in thread | raw e-mail | index | archive | help
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, ...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20151005042129.1f153ec6.freebsd>