我有一个这样的 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/