我正在逐行读取bash中的文件。 我需要打印具有以下格式的行:
不在乎<<<至少有一个人物>>>不在乎。
这些都是我尝试过的方式,但没有一个能够工作:
if [[ $line =~ .*<<<.+>>>.* ]]; then echo "$line" fi这有不正确的语法
这两个有正确的语法不起作用
if [[ $line =~ '.*<<<.+>>>.*' ]]; then echo "$line" fi还有这个:
if [[ $line == '*<<<*>>>*' ]]; then echo "$line" fi那么如何告诉bash只打印那种格式的行? PD:我已测试并打印所有线路工作正常。
I'm reading a file in bash, line by line. I need to print lines that have the following format:
don't care <<< at least one character >>> don't care.
These are all the way which I have tried and none of them work:
if [[ $line =~ .*<<<.+>>>.* ]]; then echo "$line" fiThis has incorrect syntax
These two have correct syntax don't work
if [[ $line =~ '.*<<<.+>>>.*' ]]; then echo "$line" fiAnd this:
if [[ $line == '*<<<*>>>*' ]]; then echo "$line" fiSo how to I tell bash to only print lines with that format? PD: I have tested and printing all lines works just fine.
最满意答案
为了获得最大的兼容性,将单个引号中的正则表达式模式定义为单独的变量始终是一个好主意,然后使用它不加引号。 这对我有用:
re='<<<.+>>>' if [[ $line =~ $re ]]; then echo "$line" fi顺便说一下,我摆脱了多余的领先/尾随.* 。
当然,我假设您有正当理由以原生bash处理文件(如果没有,只需使用grep -E '<<<.+>>>' file )
For maximum compatibility, it's always a good idea to define your regex pattern as a separate variable in single quotes, then use it unquoted. This works for me:
re='<<<.+>>>' if [[ $line =~ $re ]]; then echo "$line" fiI got rid of the redundant leading/trailing .*, by the way.
Of course, I'm assuming that you have a valid reason to process the file in native bash (if not, just use grep -E '<<<.+>>>' file)
更多推荐
发布评论