Search code examples
regexsedcutregex-greedy

How to imitate "cut -d: -f2" with sed? ("(.*):(.*):" matching too many fields)


Just to be clear: I am testing my code on /etc/passwd. I am trying to cut second column from text with sed (it's an exercise from my teacher, that's why I'm not using anything else). I tried using

sed 's/\(.*\):\(.*\):\(.*\)/\2/' /etc/passwd

but it's cutting the next to last column, probably because sed is taking all characters until it finds two last ":". How can i cut second column without specifying how many of them will be in file?


Solution

  • As you identified, .* can match any number of characters, including :s.

    [^:]*, by contrast, matches everything except a :, so it isn't prone to this.

    As Wiktor points out in comments, then:

    sed -Ee 's/^([^:]*):([^:]*):.*/\2/' <<<'one:two:three:four'
    

    ...correctly returns two.