bash - 搜索特定字符串时查找行首

标签 bash loops

我有这样一个文件:

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/

相关文章:

c++ - 如何优化这个程序?

通过 shell 脚本的 MySQLDump 没有被执行,为什么?

linux - 替换所有\\with/in 文件和子目录

bash - 使用 env 为子 shell 设置变量有优势吗?

matlab - 使用循环将元素添加到 MATLAB 中的现有向量

PHP 包装每 4 个元素

javascript - For 循环后返回数组

linux - 一个 Bash 脚本可以启动多个其他 Bash 脚本吗?

Bash 转置无法正常工作

java - 当Java中的谐波级数达到指定目标时,如何停止对其求和?