Hello Im fairly familiar with using the sed command for substitution, however I have been passed a script which checks the logged on username and directory type with a sed section which I cant figure out. The sed function has me baffled and I cant find out from the man page what its trying to do with the output.
directoryType=`dscacheutil -cachedump -entries user | sed -n "/$username/{g;1!p;};h" | awk '{print $9}'`
If it matches, swaps the pattern space with the contents of the hold buffer, and prints it (if it's not the first line of the file, in which case the hold buffer would be empty):
{g;1!p;}
It then puts the current line (the pattern space) into the hold space:
/$username/{g;1!p;};h
Basically, it remembers the previous line, and prints that when username matches.
This is a bit long-winded, but you work through what the sed is doing:
$ dscacheutil -cachedump -entries user
1 Cache entries (ordered as stored in the cache):
2
3 Category Best Before Last Access Hits Refs TTL Neg DS Node
4 ---------- ------------------ ------------------ -------- ------ -------- ----- ---------
5 User 02/21/10 20:45:00 02/21/10 19:56:00 96 1 3600 /Local/Default
6 Key: pw_name:nobody
7
8 User 02/21/10 20:45:00 02/21/10 19:56:00 35 1 3600 /Local/Default
9 Key: pw_name:scott
10
11 User 02/21/10 20:43:52 02/21/10 19:56:20 32 1 3600 /Local/Default
12 Key: pw_uid:501
13
14 User 02/21/10 20:45:00 02/21/10 19:56:00 145 1 3600 /Local/Default
$ username=scott
$ dscacheutil -cachedump -entries user | sed -n "/$username/{g;1!p;};h" | awk '{print $9}'
Sed on Line: 1
Pattern space: Cache entries (ordered as stored in the cache):
Hold space: <empty> (can't be any previous line in the hold buffer)
Sed on Line: 2
Pattern space: <empty> (line 2 is blank)
Hold space: Cache entries (ordered as stored in the cache): (previous line)
Sed on Line: 3
Pattern space: Category Best Before Last Access Hits Refs TTL Neg DS Node
Hold space: <empty>
Sed on Line: 4
Pattern space: ---------- ------------------ ------------------ -------- ------ -------- ----- ---------
Hold space: Category Best Before Last Access Hits Refs TTL Neg DS Node
Sed on Line: 5
Pattern space: User 02/21/10 20:45:00 02/21/10 19:56:00 96 1 3600 /Local/Default
Hold space: ---------- ------------------ ------------------ -------- ------ -------- ----- ---------
Sed on Line: 6
Pattern space: Key: pw_name:nobody
Hold space: User 02/21/10 20:45:00 02/21/10 19:56:00 96 1 3600 /Local/Default
Sed on Line: 7
Pattern space: <blank>
Hold space: Key: pw_name:nobody
Sed on Line: 8
Pattern space: User 02/21/10 20:45:00 02/21/10 19:56:00 35 1 3600 /Local/Default
Hold space: <blank>
Sed on Line: 9 <<--- Match found, print hold space, to awk, print $9 - /Local/Default
Pattern space: Key: pw_name:scott
Hold space: User 02/21/10 20:45:00 02/21/10 19:56:00 35 1 3600 /Local/Default
(the hold space for each line is the pattern space of the previous line)