cptalpdeniz
cptalpdeniz

Reputation: 389

Doing pattern matching with REGEX in SED results in unterminated `s' command

I have a csv file with data in with (which has : as delimiter). An example line is would be,

Vinh Tranh:438-910-7449:8235 Maple Street, Wilmington, VM 29085:9/23/63:68900

Now I need to print all lines that have 11 or 12 after the 3rd : character. I wrote my own Regex but when I write this to sed command it doesn't work?

$ sed -n -E 's#(?:.*?\:){3}(11)\s*\/#p' datebook
sed: -e expression #1, char 25: unterminated `s' command

Upvotes: 1

Views: 220

Answers (1)

Sundeep
Sundeep

Reputation: 23677

sed -n -E 's#(?:.*?\:){3}(11)\s*\/#p'

There are several issues with this command:

  • s command is for substitution, don't use it for filtering
  • when you need another delimiter for filtering, you have to escape the first one
    • and you still escaped the / anyway
  • sed doesn't support non-capturing group or non-greedy quantifiers
    • and non-greedy isn't suited here anyway, since it will try to match as long as there minimum three : characters - you need a negated character class to restrict to first three : characters
  • you need to anchor the search, otherwise it will match anywhere in the line, not just from start of line

Here's a solution based on your description of getting lines with 11 or 12 after the third :

sed -nE '/^([^:]*:){3}1[12]\//p'

# with different delimiter
sed -nE '\#^([^:]*:){3}1[12]/#p'

grep is simpler to use:

grep -E '^([^:]*:){3}1[12]/'

And awk is the best suited in my opinion, since this is a field based processing:

awk -F: '$4 ~ /^1[12]\//'

I haven't used \s in the above solutions, you can add if needed.

Upvotes: 1

Related Questions