Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the position of specific word in a txt file using awk?

I need to find the position of a certain word in a text file
I tried to do something like this but it didn’t work (no any output):
For example txt file contains:

A    B    C
Tarun    A12    1
Man    B6    2
Praveen    M42    3

So I need to find a word ,,Tarun" position
the output should be: Row: 2 Column 1
But instead I get no output

read -p "Write a word: " word
   awk '{ 
    for(i=1;i<=NF;i++)
        if($i == '$word')
            print "Row: " NR, "Column: " i 
}' file.txt

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The only problems in the original code stem from passing the variable word from bash to awk incorrectly.

Fixing this to use awk -v var="value" as taught by the answers to the preexisting question How do I use shell variables in an awk script?, the code works as-intended:

#!/usr/bin/env bash

word='Tarun'

# using this instead of a file so we can run in sandboxes without write support
getInput() { cat <<'EOF'
A    B    C
Tarun    A12    1
Man    B6    2
Praveen    M42    3
EOF
}

awk -v word="$word" '{ 
    for(i=1;i<=NF;i++)
        if($i == word)
            print "Row: " NR, "Column: " i 
}' <(getInput)

correctly emits:

Row: 2 Column: 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading