如何使用grep检查字符串长度? [英] How to check the string length using grep?
问题描述
我有很多Teradata SQL文件.示例文件如下所示:
I have a lot of Teradata SQL files. The example file look like below:
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个符号. 我已经创建了一些抓点,但是它们都不起作用,我也不知道为什么.我做错了什么?
I want to create a grep method which can count the length of the table name, which can't exceed 10 signs. I have created a few greps, but none of them work, and I don't know why. What I have done wrong?
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
我曾经使用过的其他抱怨:
other greps which I used:
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个合法字符,然后再匹配一个不同的字符.
There are a couple of problems with your attempts. Firstly, it looks like you're escaping the [
in some of your bracket expressions, which means that the [
will be interpreted as a literal character instead. Secondly, you need to take care to match 1 to 10 legal characters, followed by a different character.
此模式可以满足您的要求(我删除了-q
,以便您可以看到匹配的表定义):
This pattern does what you want (I removed the -q
so that you can see which table definitions match):
$ 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个字母数字字符或下划线,后跟一个不同的字符,这意味着较长的表名不再匹配.
This pattern matches 1 to 10 alphanumeric characters or underscores, followed by a different character, meaning that the longer table names no longer match.
由于大小写不一致,您可能还应该将-i
开关用于grep,以启用不区分大小写的匹配.否则,任何使用"TABLE"的定义都将不匹配.
As it appears that the casing is inconsistent, you should probably also use the -i
switch to grep, to enable case-insensitive matching. Otherwise, any definitions that use "TABLE" would not match.
这篇关于如何使用grep检查字符串长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!