0

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
MHmmm
  • 15
  • 5
  • "Position" singular? If you really want to stop at only one you should make the program exit after finding a match. – Charles Duffy Dec 12 '22 at 20:33
  • Anyhow, the _most immediate_ problem is that you should be using `awk -v` to pass variables from bash to awk. `'$word'` is an antipattern that exposes you to injection attacks – Charles Duffy Dec 12 '22 at 20:34
  • "it didn't work" is not a very useful description. Error message? expected output versus actual output? – j_b Dec 12 '22 at 20:34
  • 1
    please update the question to expand on *`it didn't work`* ... error message? no output? wrong output? something else? also provide a sample input file, an example `word`, and the (correct) expected output – markp-fuso Dec 12 '22 at 20:35
  • To be clear about why your original code didn't work: The single quotes in `'$word'` are eaten by the shell so there are no quotes in awk, so the line ends up as `if($i == Tarun)`; there's no awk variable named `Tarun`, so `$i == Tarun` is never true; above and beyond the security issues (and there _are_ serious security issues there). – Charles Duffy Dec 12 '22 at 20:48
  • ...re: above assertion of security issues, consider what happens when the user says the word they're searching for is `system("rm -rf ~")` -- which is perfectly valid awk code! Even if you add literal quotes, a user can just escape them. – Charles Duffy Dec 12 '22 at 20:49

1 Answers1

1

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
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441