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
>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