Regular Expressions: Marking Up a Document with sed

Hands-On Lab

 

Photo of Elle Krout

Elle Krout

Content Team Lead in Content

Length

01:00:00

Difficulty

Intermediate

Regular expressions can be especially powerful when paired with any kind of scripting or text processing language, such as sed. In this learning activity, we craft a script to add formatting to a plain-text file using various regular expressions concepts alongside sed to create a Latex-friendly document.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Regular Expressions: Marking Up a Document with sed

Introduction

Regular expressions can be especially powerful when paired with any kind of scripting or text processing language, such as sed. In this learning activity, we craft a script to add formatting to a plain-text file using various regular expressions concepts alongside sed to create a Latex-friendly document.

Solution

Begin by logging in to the lab server using the credentials provided on the hands-on lab page:

ssh cloud_user@PUBLIC_IP_ADDRESS

It may be helpful to have two terminal windows open for this lab; one to write the script and the other to test.

Create sed script

Create a sed script that meets all the requirements listed in the instructions.

Create the file:

vim latex.sed

Include the following script:

#! /usr/bin/sed

1s/(.+)/\documentclass{article}n\usepackage{hyperref}n\begin{document}n\title{1}/
s/^[IVXLDCM]+. (.+)/\section{1}/
/[root@red-hat.+?]#/ {
  N
  s/([root@red-hat.+?]#.+(n[root@red-hat.+?]#.+)?)/\begin{verbatim}n1n\end{verbatim}/
}
s/(t|    )(.+)/\begin{verbatim}n2n\end{verbatim}/
s/(bw+.cfb)/texttt{1}/g
s/`(.+?)`/\texttt{1}/g
$ a \end{document}

Convert the example file

Convert mail-forwarding.txt to mail-forwarding.latex with the sed script developed in the hands-on lab.

sed -E -f latex.sed mail-forwarding.txt > mail-forwarding.latex

Conclusion

Congratulations — you've completed this hands-on lab!