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

Shell How to check if a pattern exists in a line in file

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

一个文件在第 28 行有以下行:

page.sysauth = {"Admin"}

我需要检查 "Admin" 是否存在于此 特定行 (它可能存在也可能不存在于整个文件的多个位置。)

谢谢

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

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

使用 awk 你可以这样做:

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

或使用sed | grep:

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

使用 awk

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

这可能适合您 (GNU sed):

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