如何使用grep检查字符串长度



我有很多Teradata SQL文件。示例文件如下所示:

create multiset volatile table abcde_fghijk_lmnop as(
select 
a.oppnl3_budssstr as nip,
from T45_BACKJJU_33KUT.BRANDFO9 a 
) with data on commit preserve rows;
create multiset volatile table mari_lee as(
select 
b.getter3,
from maleno_fugi75_pratq b
) with data on commit preserve rows;
create multiset table blabla1 as (
select
a.atomic94,
from  b4ty7_manto.pretyu59_bxcx a
) with data on commit preserve rows;
CREATE multiset table blablabla2 AS ( 
SELECT
a.prompter_to12 
FROM tresh_old44 a
) WITH data on commit preserve rows;
CREATE multiset table blablablabla3 AS ( 
SELECT
c.future_opt86 
FROM GFTY_133URO c
) WITH data on commit preserve rows;

我想创建一个grep方法,它可以计算表名的长度,不能超过10个符号。我创建了一些greps,但是没有一个能工作,我也不知道为什么。我做错了什么?

for f in /path/to/sql/files/*.sql; do
    if grep -q ' table {1,10}' "$f"; then
        echo "correct length of table name $f"
    fi
done

我使用的其他greps:

if grep -q ' table {1,10} as ' "$f"; then
if grep -q ' table [[:alnum:]]{1,10} ' "$f"; then
if grep -q ' table[[:space:]][[:alnum:]]{1,10} ' $f; then

您的尝试有几个问题。首先,看起来您在一些括号表达式中转义了[,这意味着[将被解释为一个文字字符。其次,您需要注意匹配1到10个合法字符,后面跟着一个不同的字符。

这个模式完成了您想要的(我删除了-q,以便您可以看到哪些表定义匹配):

$ grep ' table [[:alnum:]_]{1,10}[^[:alnum:]_]' file
create multiset volatile table mari_lee as(
create multiset table blabla1 as (
CREATE multiset table blablabla2 AS (

此模式匹配1到10个字母数字字符或下划线,后面跟着一个不同的字符,这意味着较长的表名不再匹配。

由于看起来大小写不一致,您可能还应该使用-i切换到grep,以启用不区分大小写的匹配。否则,任何使用"TABLE"的定义都将不匹配。

使用grep字边界只列出有效的表名:

grep -E 'table +.{1,10}b' "$f"
create multiset volatile table mari_lee as(
create multiset table blabla1 as (
CREATE multiset table blablabla2 AS (

使用-q抑制输出并检查返回状态:

grep -qE 'table +.{1,10}b' "$f"

最新更新