我有这样一个文件:
1 Role A
2 Role b
我想做的是搜索字符串“Role A”并在变量中返回值 1。
所以像下面这样:
if grep "$i" role_info.txt
then
<assign a variable the number associated with the string>
else
<no search string found - do something else>
fi
最佳答案
如果列用制表符分隔,那么您可以:
role='Role A'
number=$(awk -v role="$role" -F '\t' '$2==role {print $1}' role_info.txt)
如果只是空格,试试:
role='Role A'
number=$(grep "$role" role_info.txt | cut -d' ' -f1)
无论哪种方式,您都可以检查是否找到匹配项:
if [[ -n $number ]]; then
# number found
else
# not found
fi
另一种选择是:
while read number role; do
if [[ $role == 'Role A' ]]; then
# match found
fi
done < role_info.txt
这会更健壮一些:角色必须是行中的第二个项目;它不能处于第一位置。
关于bash - 搜索特定字符串时查找行首,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30920095/