grep1-5 Exercise 1: ids and a Name Chosen by Something Later in the Line ========================================================================= cat > users.txt <<'EOF' user=bob id=42 role=admin user=alice id=7 role=user user=carol id=19 role=user EOF echo "ids:" grep -oP 'id=\K\d+' users.txt echo echo "names of users whose role is user:" grep -oP 'user=\K\w+(?=.*role=user)' users.txt Output: ids: 42 7 19 names of users whose role is user: alice carol WHY THIS WORKS AS AN ANSWER --------------------------- id=\K\d+ matches 'id=' and then \K throws it away, so only the digits are printed. In the second command the name is what we print; (?=.*role=user) is a lookahead that looks FORWARD along the line for role=user without including it in the output. Only alice and carol qualify. A lookbehind cannot do the second job: the condition (role=user) comes AFTER the name on the line, and a lookbehind can only look at what is before the match. Even for conditions before the match, a lookbehind has to be a fixed length (Chapter 5), while \K has no such limit, which is why \K is the usual way to say 'start the output here'.