linux - bash:grep 通配符开始和结束

标签 linux bash shell grep

我有一个这样的 bash 脚本:

TABLE_TO_IGNORE=$(mysql -u $DBUSER -p$DBPASS -h $DBHOST  -N <<< "show tables from $DBNAME" | grep "^$i" | xargs);

目前我只能 grep 开头的文本。判断文本结尾的代码怎么写?

假设 1:

我的 $i 是: 测试1_* tb2_* tb3_*

后面有 * 的部分,它将被 grep 为以这些值开头的文本

假设 2:

我的 $i 是: *_sometext1 *sometext2

如果前面有 *,它将被 grep 为以这些值结尾的文本。

我知道这个:
grep '^sometext1' files = 'sometext1' 在一行的开头
grep 'sometext2$' files = 'sometext2' 在行尾

问题是:我如何将 if else 写入我的 bash 代码以识别 * 在前面或后面?

注意:您可以忽略我的 bash 代码,我只需要 if else 条件来确定“*”在字符串的前面还是后面。

任何帮助都会很棒。

谢谢

最佳答案

你可以试试这段代码。

#!/bin/bash

stringToTest="Hello World!*" 

echo $stringToTest | grep "^\*.*" > /dev/null
if [ $? -eq 0 ]; then
     echo "Asterisk is at the front" 
fi

echo $stringToTest | grep "^.*\*$" > /dev/null 
if [ $? -eq 0 ]; then
     echo "Asterisk is at the back" 
fi

如这段代码所示,我使用退出代码 ($?) 来确定正则表达式是否与字符串匹配。如图man grep :

Normally, exit status is 0 if selected lines are found and 1 otherwise.

希望这对您有所帮助。

关于linux - bash:grep 通配符开始和结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19262669/

相关文章:

node.js - 乌类图 : NPM EACCES error though I changed folder ownership

bash - 暴力破解 16 个字符的 key 需要多长时间

cp 和 mv 中的 linux 通配符用法

c++ - shmat 返回的指针指向地址空间的末尾,这会导致段错误

linux - 将一个文件的所有内容分别加载到各个文件中

arrays - bash:为什么 ${@:-1} 的值与 ${@: -1} 不同?

arrays - awk 相当于 C 中的 LTRIM 函数

python - Lua脚本不会执行python脚本

regex - 如何在 te gnome-terminal 中使用 sed 命令实现语法高亮?

c++ - 如何仅从 linux SO 库中导出某些函数?