ChewySalmon
ChewySalmon

Reputation: 614

AWK Line of code printing to my output file when no print has been stated

I'm intending to match some set of characters to the middle of a word, where I check the start and end of the word (it can't match the first or last characters otherwise my goal is void). Then I check if it exists in the word using

$1~/xampl/

The line of code I've come up with works perfectly, except when using

awk -f awkfile inputfile > outputfile

I want it to increment exists and not print, but it prints every time it matches... Am I missing something?

Upvotes: 0

Views: 88

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

awk programs follow this structure:

CONDITION { ACTIONS } [ CONDITION { ACTIIONS } ... ]

where either CONDITION or ACTIONS are optional. If the CONDITION is missing, like this:

awk '{ print }'

awk will assume the CONDITION to be true and execute the { print } on every line of input.

If the ACTIONS are missing, like this (similar to your case):

awk '$1~/xampl/'

awk will run the default action, which is {print}. If you don't want to print but just increment you need to add an action, like this:

awk '$1~/xampl/ { c++ }'

Upvotes: 1

randomir
randomir

Reputation: 18687

If I understood your question correctly, your expression to match the word only when it appears in the middle of the first field is wrong. You're suffix index is off by two; it should be:

#!/usr/bin/awk -f
"xampl"!=substr($1, 1, length("xampl")) && "xampl"!=substr($1, length($1)-length("xampl")+1, length("xampl")) && $1~/xampl/ {exists+=1}

which can be shortened to:

#!/usr/bin/awk -f
$1~/.+xampl.+/ {exists++}

However, those scripts have no side-effects, i.e. all you do is increment a variable, but you never print it. This leads me to believe your error is actually in some other part of the script you are not showing us. Regardless, your awk program should not behave differently when invoked from a file.

Upvotes: 0

Related Questions