34.14 Transforming Part of a LineThe transform command, y ( 34.12 ) , acts on the entire contents of the pattern space. It is something of a chore to do a letter-by-letter transformation of a portion of the line, but it is possible (though convoluted) as the following example will demonstrate. [The real importance of this example is probably not the use of the y command, but the use of the hold space to isolate and preserve part of the line. - TOR ] While working on a programming guide, we found that the names of statements were entered inconsistently. They needed to be uppercase, but some were lowercase while others had an initial capital letter. While the task was simple - to capitalize the name of the statement - there were nearly a hundred statements and it seemed a tedious project to write that many explicit substitutions of the form:
s/find the Match statement/find the MATCH statement/g The transform command could do the lowercase-to-uppercase conversion but it applies the conversion to the entire line. The hold space makes this task possible because we use it to store a copy of the input line while we isolate and convert the statement name in the pattern space. Look at the script first:
# capitalize statement names /the .* statement/{ h s/.*the \(.*\) statement.*/\1/ y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/ G s/\(.*\)\n\(.*the \).*\( statement.*\)/\2\1\3/ }
The address limits the procedure to lines that match
Let's look at a test run. Here's our sample file:
find the Match statement Consult the Get statement. using the Read statement to retrieve data Running the script on the sample file produces:
find the MATCH statement Consult the GET statement. using the READ statement to retrieve data As you can see from this script, the hold space can be skillfully used to isolate and manipulate portions of the input line. - from O'Reilly & Associates' sed & awk |
|