LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   awk patterns (https://www.linuxquestions.org/questions/linux-newbie-8/awk-patterns-4175619329/)

goofygoober 12-10-2017 10:45 AM

awk patterns
 
Hey there, I'm trying to figure out what makes an awk pattern.
I understand generally it goes
pattern {action}
for example
/blah/ {
printf $1;
}

but do functions also count as patterns?
if i have:
while (rose is red){
printf $1;
}
is the "while" considered a pattern in this case?

also, what is an empty pattern? I've tried searching around but keep getting brought to
https://www.gnu.org/software/gawk/ma...ode/Empty.html
which provides a single line awk command but i'd like to see an empty pattern within a script file.

pan64 12-10-2017 10:58 AM

usually awk will process a file (or stdin) line by line.
as you wrote, awk works like:
Code:

pattern { action }
where pattern means you want to select which lines should be involved. Empty or missing pattern means you want to process all the lines - or input records.
Pattern always written as /<string>/ so it is a string between slashes. while is not a pattern.

goofygoober 12-10-2017 11:00 AM

Quote:

Originally Posted by pan64 (Post 5791491)
usually awk will process a file (or stdin) line by line.
as you wrote, awk works like:
Code:

pattern { action }
where pattern means you want to select which lines should be involved. Empty or missing pattern means you want to process all the lines - or input records.
Pattern always written as /<string>/ so it is a string between slashes. while is not a pattern.

Ah! Okay!
So then
{
printf $1
}
IS considered a pattern block? just an empty one?

Turbocapitalist 12-10-2017 11:07 AM

The pattern is still considered to be there it's just that if it is empty then it happens to always evaluate to true and thus always excutes the action.

goofygoober 12-10-2017 11:08 AM

Quote:

Originally Posted by Turbocapitalist (Post 5791496)
The pattern is still considered to be there it's just that if it is empty then it happens to always evaluate to true and thus always excutes the action.

Awesome, thanks for the info!

Turbocapitalist 12-10-2017 11:22 AM

No problem. Be sure to test things in awk as you think of them. It's pretty simple and practice is the best way of learning. There are a lot of shortcuts, such as the empty pattern, that can be used to great advantage.

Also, the manual page is also worth visiting frequently but the different awk variants have different quality of manual pages.


All times are GMT -5. The time now is 11:15 AM.