💾 Archived View for yasendfile.org › TipTricks › sed.gmi captured on 2023-04-19 at 22:21:40. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2022-07-16)

-=-=-=-=-=-=-

Sed - Gnu Stream Editor - Tips and Tricks

Written by Wim Stockman - on 18 June 2022

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

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

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″

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

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