Mayur Buragohain
Mayur Buragohain

Reputation: 1615

regex matching for lines from file

I have a file that reads something like below:

Change 305034 on 2017/04/26 by jdoe@BP
Change 304966 on 2017/04/26 by adoe@adoe
Change 304880 on 2017/04/25 by cm@cpu_jar_process_main_8.30.0.9
Change 304843 on 2017/04/25 by mdoe@BP

I need to pick lines that has cm@ in it. I have generated a regex to match it.

Change\s[0-9]+\son\s[0-9]{4}\/[0-9]{2}\/[0-9]{2}\sby\scm

I have tested it https://regex101.com/ and it works fine.

Now I want to use a shell script to do the matching. The script is as follows-

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    # echo "Text read from file: $line"
    # Change\s[0-9]+\son\s[0-9]{4}\/[0-9]{2}\/[0-9]{2}\sby\scm"
    if [[ "$line" =~ "Change\s[0-9]+\son\s[0-9]{4}\/[0-9]{2}\/[0-9]{2}\sby\scm" ]]; then
        echo $line
    fi

done < "output.txt"

But it does not match any line.

I found that if i use if [[ "$line" =~ "Change" ]]; then it is returning results. But no results when I use the full regex pattern. I am assuming that there is a syntax error.

Can someone point out what is it that I am doing wrong?

Upvotes: 0

Views: 892

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

If your input file contains lines in similar format like Change 305034 on 2017/04/26 by ... - there's pretty short awk solution:

awk '$6~/^cm@/' output.txt

The output:

Change 304880 on 2017/04/25 by cm@cpu_jar_process_main_8.30.0.9

Upvotes: 2

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

if [[ "$line" =~ 'Change\s[0-9]+\son\s[0-9]{4}\/[0-9]{2}\/[0-9]{2}\sby\scm' ]]; then
                 ^                                                        ^
                 |                                                        |
                  `- Use single quotes to avoid escaping interpretation  -'

Upvotes: 1

Related Questions