Yehuda
Yehuda

Reputation: 1893

Sed occasionally missing a capture group

I'm writing a script that will allow users to apply their own list of ACLs more simply as part of a broader directory creation script. Users will input either u/user or g/group, their name, and the basic options they want from RWX. I'm using sed to transform the input to a proper NFSv4 ACL:


sed -E 's/^/A:/;s/(u|user|roup):([A-Za-z0-9]*):(.*)/:\[email protected]:\3/'

When I input a list as follows to test: u:user1:RWX,g:group1:RX, I do see correct output of the user: A::[email protected]:RWX, but the group does not apply properly: A:g:group1:RX instead of A:g:[email protected]:RX. When I use group:group1::RX it properly returns A:g:[email protected]:RX. I'm guessing it's because the g is not recognized as the first capture group, but I can't think how to correct that. Any tips?

Upvotes: 1

Views: 60

Answers (1)

choroba
choroba

Reputation: 242208

You can use optional capture groups that you don't use in the replacement part to remove parts of the input and nested capture groups to remember just parts of the matched substrings:

printf '%s\n' 'u:user1:RWX' 'g:group1:RX' 'group:group1:RX' \
| sed -E 's/^/A:/;s/(u|(g)(roup)?):([A-Za-z0-9]*):(.*)/\2:\[email protected]:\5/'

Output:

A::[email protected]:RWX
A:g:[email protected]:RX
A:g:[email protected]:RX

Upvotes: 2

Related Questions