From dbdc75e9059ed570191fb685c5c49e78ec619b3e Mon Sep 17 00:00:00 2001 From: Jenss21025 Date: Wed, 9 Dec 2015 16:15:13 +0100 Subject: [PATCH] Insert sed Insert sed based on man pages (http://linux.die.net/man/1/sed) and an introduction by Bruce Barnett (http://www.grymoire.com/Unix/Sed.html). --- shell_tools_101.rst | 74 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/shell_tools_101.rst b/shell_tools_101.rst index 8f658c00..03a50f7a 100644 --- a/shell_tools_101.rst +++ b/shell_tools_101.rst @@ -611,7 +611,79 @@ For example: sed --- -.. todo:: Only talk about replacing text for now? It's the most common / needed piece of sed at this level. + +Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors + +Synopsis + +.. code-block:: console + + $ sed [OPTION]... {script-only-if-no-other-script} [input-file]... + + Sed has several commands, but most people only learn the substitute command: s. The substitute command changes all occurrences of the regular expression into a new value. A simple example is changing "day" in the "old" file to "night" in the "new" file: + +.. code-block:: console + + $ sed s/day/night/ new + +Or another way (for UNIX beginners), + +.. code-block:: console + + $ sed s/day/night/ old >new + +and for those who want to test this: + +.. code-block:: console + + $ echo day | sed s/day/night/ + +This will output "night". + +I didn't put quotes around the argument because this example didn't need them. If you read my earlier tutorial on quotes, you would understand why it doesn't need quotes. However, I recommend you do use quotes. If you have meta-characters in the command, quotes are necessary. And if you aren't sure, it's a good habit, and I will henceforth quote future examples to emphasize the "best practice." Using the strong (single quote) character, that would be: + +.. code-block:: console + + $ sed 's/day/night/' new + +I must emphasize that the sed editor changes exactly what you tell it to. So if you executed + +.. code-block:: console + + $ echo Sunday | sed 's/day/night/' + +This would output the word "Sunnight" because sed found the string "day" in the input. + +Another important concept is that sed is line oriented. Suppose you have the input file: + +one two three, one two three +four three two one +one hundred + +and you used the command + +.. code-block:: console + + $ sed 's/one/ONE/'