Nike
Nike

Reputation: 43

Assign the value of awk-for loop variable to a bash variable

content within the tempfile

123 sam moore IT_Team
235 Rob Xavir Management

What i'm trying to do is get input from user and search it in the tempfile and output of search should give the column number

Code I have for that

#!/bin/bash
set -x;
read -p "Enter :" sword6;
awk 'BEGIN{IGNORECASE = 1 }
{
for(i=1;i<=NF;i++) {
    if( $i ~ "'$sword6'$" )
            print i;
    }
} ' /root/scripts/pscripts/tempprint.txt;

This exactly the column number

Output

Enter : sam
2

What i need is the value of i variable should be assigned to bash variable so i can call as per the need in script.

Any help in this highly appreciated.

I searched to find any existing answer but not able to find any. If any let me know please.

Upvotes: 0

Views: 1206

Answers (4)

ctac_
ctac_

Reputation: 2471

If tempprint.txt is big

awk -v w="$word6" '
BEGIN { IGNORECASE = 1 }
"$0 ~ \\<w\\>" {
    for(i=1;i<=NF;i++)
        if($i==w)print i
}' tempprint.txt

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133428

Following script may help you on same too.

cat script.ksh
echo "Please enter the user name:"
read var
awk -v val="$var" '{for(i=1;i<=NF;i++){if(tolower($i)==tolower(val)){print i,$i}}}'   Input_file

Upvotes: 1

chepner
chepner

Reputation: 530940

You just need to capture the output of awk. As an aside, I would pass sword6 as an awk variable, not inject it via string interpolation.

i=$(awk -v w="$sword6" '
        BEGIN { IGNORECASE = 1 }
        { for (i=1;i<=NF;i++) {
            if ($i ~ w"$") { print i; }
          }
        }' /root/scripts/pscipts/tempprint.txt)

Upvotes: 1

Kent
Kent

Reputation: 195029

  • first of all, you should pass your shell variable to awk in this way (e.g. sword6)

    awk -v word="$sword6" '{.. if($i ~ word)...}`...
    
  • to assign shell variable by the output of other command:

    shellVar=$(awk '......')
    

Then you can continue using $shellVar in your script.

regarding your awk codes:

  • if user input some special chars, your script may fail, e.g .*
  • if one column had matched userinput multiple times, you may have duplicated output.
  • if your file had multi-columns matching user input, you may want to handle it.

Upvotes: 1

Related Questions