Friday 21 December 2018

macos - Merge two separate sed expressions into one?


I'm reading the RealName from dscl for various users. Depending on the user, the output can be one of the following two:


RealName: 

Or:


RealName:


So I have sed -e 's|^[RealName:[:space:]]*||g' -e '/^$/d' to get just the in either case. I'm new to regular expressions, so I'm having trouble merging the two expressions. Any suggestions? (Just doing it for fun. That command works just fine as-is.)



Answer




  1. Match a line that has only RealName: and spaces, append the Next line to the pattern space.

  2. remove RealName: and the newline.

  3. What's left, should be


Since the command order matters, the next select-lines command that matches anything ((.*)) on a line that starts with RealName: will have "something interesting" after the matched regex.



  1. Match all other lines starting with RealName: and do the same without newlines

  2. delete empty lines.




sed -E -e '
/^RealName:\s*$/{ N; s/RealName:.*\n// };
/^RealName:(.*)/{ s//\1/ };
/^$/d
' ~/tmp/RealName

If the substitute command has nothing in the match field, it defaults to the previous select-lines command's regex.


/hello world/{ s//bye mars/ }    
<=>
/hello world/{ s/hello world/bye mars/ }

No comments:

Post a Comment

Where does Skype save my contact&#39;s avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...