我有一个这样的bash脚本:
TABLE_TO_IGNORE=$(mysql -u $DBUSER -p$DBPASS -h $DBHOST -N <<< "show tables from $DBNAME" | grep "^$i" | xargs);
目前我只能从 grep 开始文本。如何编写确定文本结尾的代码?
假设 1:
我$i是:test1_*tb2_*tb3_*
在后面加上 *,它将 grep 作为以这些值开头的文本
假设 2:
我$i是:*_sometext1*一些文本2
如果 * 位于前面,它将 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 所示:
通常,如果找到所选行,则退出状态为 0,如果找到 1 否则。
希望这有帮助。