如何用awk遍历字段并输出含dog的行及对应字段编号
Using Awk to Find Lines with "dog" and Their Field Numbers via Loop
Absolutely, you can loop through each field in awk to achieve this—your idea of iterating through fields is spot-on, we just need to fix a few syntax issues from your example code.
Here's the working awk command that does exactly what you want:
awk '{ # Loop through every field in the current line for (i = 1; i <= NF; i++) { # Check if the i-th field is exactly "dog" if ($i == "dog") { # Print the full line and the field number print $0, "Field number:", i } } }' abc.txt
Let's break down why this works:
NFis awk's built-in variable that holds the number of fields in the current line (no$before it—using$NFwould give you the value of the last field instead of the count).- The
forloop runs from field 1 to the total number of fields (NF), so we check every field in the line. $irefers to the value of the i-th field—this is how you access individual fields dynamically in awk.- When we find a match,
print $0outputs the entire line, followed by the field number where "dog" was found.
Testing with your sample input:
If abc.txt contains:
I have a dog
The dog is goood
The cat runs well
The output will be:
I have a dog Field number: 4 The dog is goood Field number: 2
Fixes from your original code:
- Instead of
j = $NF, useNFdirectly (since$NFis the value of the last field, not the count of fields). - Replace
$N$iwith$i—that's the correct way to reference the i-th field in awk. - You don't need
more abc.txt |—awk can read the file directly by passing it as an argument.
内容的提问来源于stack exchange,提问作者awkward sedist
相关产品推荐
相关产品推荐

