Shell如何检查文件中的行中是否存在模式

时间:2015-09-23 10:00:08

标签: bash shell awk sed sh

我们如何检查文件中特定行号的行中是否存在模式或字符串:

文件在第28行有以下行:

page.sysauth = {“Admin”}

我需要检查此特定行是否存在“管理员”(整个文件中的多个位置可能存在也可能不存在。)

谢谢

4 个答案:

答案 0 :(得分:2)

使用awk你可以这样做:

awk '/Admin/ && NR == 28 { print "exists" }' file

或使用sed | grep

sed '28q;d' file | grep -q 'Admin' && echo "exists"

答案 1 :(得分:1)

使用head& tail提取该行,然后grep检查存在:

if head -n28 file | tail -n1 | grep -q '"Admin"' ; then
    echo Present
else
    echo Not present
fi

答案 2 :(得分:1)

使用awk

awk 'NR==28{print (/Admin/?"":"Not ")"present"}' file

答案 3 :(得分:0)

这可能适合你(GNU sed):

sed -n '$q1;28{/Admin/q0;q1}' file && echo present || echo not present
相关问题