I have just come through a sed tutorial article. Can somebody please explain this command for me (it changes alphabet to upper case after period)

sed -E 's/(^[a]|\. [a-z])/\U&\E/g' filename.txt
  • 4
    I personally don't mind helping out with homework, but it would be interesting to hear your own thoughts about this first. Best regards. – maulinglawns Nov 12 '16 at 19:27

The tutorial that you linked to is very superficial.

If you want to use sed seriously, I suggest http://www.grymoire.com/Unix/Sed.html instead.

The s command in sed takes a from pattern, a to string, and optionally some flags. Traditionally these are separated by a / character but any punctuation can be used and this is sensible to do if either the from or to arguments contain / characters.

So in this case the flags are g, the from pattern is (^[a]|\. [a-z]) and the to string is \U&\E

At this point you need to know how to understand the from pattern. The () characters are used to group parts of the pattern together. The | is an or operations so this|that would match either this or that. The ^ matches the start of a line, and the [a] matches the letter a, so ^[a] matches a letter a at the start of a line. The \. matches a . character, the space matches a space, and the [a-z] matches a character between a and z inclusive (Hopefully this is all the lower case letters and nothing else). Putting this together you get \. [a-z] matches a full stop (period) followed by a space followed by a letter between a and z inclusive.

The to string \U&\E is decoded as follows. the & is the characters that matched the from pattern. The \U says to convert what follows to upper case and the \E says to end the conversion. The \U and \E are gnu extensions to sed. Here is the POSIX sed

The g flags say to repeat the matching as many times as it can and do the substitutions.

So the code you copied from the tutorial converts either a lower case a at the start of a line or a sequence of "period space lower_case_letter" to upper case.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.