bash - Grep for beginning of line while searching for a certain string -


i have file such:

1    role 2    role b 

what i'd search string "role a" , return value 1 in variable.

so following:

if grep "$i" role_info.txt     <assign variable number associated string> else     <no search string found - else> fi 

if columns delimited tabs can do:

role='role a' number=$(awk -v role="$role" -f '\t' '$2==role {print $1}' role_info.txt) 

if it's spaces, try instead:

role='role a' number=$(grep "$role" role_info.txt | cut -d' ' -f1) 

either way, can check if match found with:

if [[ -n $number ]];     # number found else     # not found fi 

another option is:

while read number role;     if [[ $role == 'role a' ]];         # match found     fi done < role_info.txt 

this bit more robust: role has second item on line; can't in first position.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -