+--------------------------------------------------+
|Sed - Gnu Stream Editor - Tips and Tricks         |
|Written by Wim Stockman - on 18 June 2022         |
+--------------------------------------------------+

____           _
/ ___|  ___  __| |
\___ \ / _ \/ _` |
___) |  __/ (_| |
|____/ \___|\__,_|

____  _                              _____    _ _ _
/ ___|| |_ _ __ ___  __ _ _ __ ___   | ____|__| (_) |_ ___  _ __
\___ \| __| '__/ _ \/ _` | '_ ` _ \  |  _| / _` | | __/ _ \| '__|
___) | |_| | |  __/ (_| | | | | | | | |__| (_| | | || (_) | |
|____/ \__|_|  \___|\__,_|_| |_| |_| |_____\__,_|_|\__\___/|_|

1. Sed: Append a prefix in front of every line of a file
--------------------------------------------------------

Example File:
▶ cat /tmp/file
Line One
Line Two
Line Three
Line Four
Line Five

▶ sed 's/^/PREFIX: /' /tmp/file

PREFIX: Line One
PREFIX: Line Two
PREFIX: Line Three
PREFIX: Line Four
PREFIX: Line Five

2. Sed: Append a postfix to every line of a file
--------------------------------------------------------
▶  sed 's/$/ : Postfix/' /tmp/file

Line One : Postfix
Line Two : Postfix
Line Three : Postfix
Line Four : Postfix
Line Five : Postfix


3. Sed: Prepend and Append to every line of a file
--------------------------------------------------------
▶ sed 's/.*/PREFIX: & :Postfix/' /tmp/file

PREFIX: Line One :Postfix
PREFIX: Line Two :Postfix
PREFIX: Line Three :Postfix
PREFIX: Line Four :Postfix
PREFIX: Line Five :Postfix

☻ The magic happens by using the ‶&″ which means : ‶the whole part of the input that was matched by the pattern″ ☻

4. Sed: Insert text before the first line
--------------------------------------------------------
▶ sed '1i Before First Line' /tmp/file

Before First Line
Line One
Line Two
Line Three
Line Four
Line Five

5. Sed: use of line number
--------------------------------------------------------
In Sed every command can be prepended by a line number.
So the command ‶i″ inserts text before so 1i - means before line 1

A special case of the line number is the ‶$″ sign which means last line.

Change last character of a file
▶  sed '$s/.$/LAST/' /tmp/file

Remove last character of a file
▶ sed '$s/.$//' /tmp/file


+--------------------------------------------------+
|Suggestions? [email protected]                |
+--------------------------------------------------+