Once you’ve mastered the basics and a few advanced patterns, sed starts to feel less like a tool and more like a language. Its syntax may be terse, but it allows for elegant and powerful transformations. This article explores even more examples of how sed can be used effectively on Debian 12, especially for creative or specialized tasks.
Let’s begin with extracting specific parts of a line. Say you have a CSV file and want only the second column. Assuming comma-separated values:
sed 's/^[^,]*,\([^,]*\).*/\1/' file.csv
Here’s the breakdown:
^[^,]*, matches the first column and comma. [^,]* matches any character except commas.
\([^,]*\) captures the second column (everything up to the next comma).
.* matches the rest of the line.
\1 replaces the entire line with the second column.
This is useful when cut isn’t flexible enough—for example, if delimiters are inconsistent.
Another handy example is wrapping each line with quotes. If you want to convert:
apple
banana
cherry
into:
"apple",
"banana",
"cherry",
You can use:
sed 's/.*/"&",/' list.txt
.* matches the whole line.
"&”` adds quotes around the entire match.
The trailing comma is appended as part of the replacement.
Suppose you want to insert a line after every 3 lines—for example, adding a divider line. Use a counter with ~:
sed 'n;n;a---' file.txt
This prints the first line normally, skips the next two with n, and then appends ---. It then repeats. This works when line structure is predictable.
To replace the last word in a line:
sed 's/\s\+\([^ \t]*\)$/ [\1]/' file.txt
This finds the final whitespace-separated word and puts it in brackets.
\s\+ matches one or more spaces or tabs.
\([^ \t]*\)$ captures the final non-whitespace sequence at the end of the line.
The replacement adds brackets around the last word.
Let’s say you want to number each line of a file:
sed = file.txt | sed 'N;s/\n/ /'
The first sed = prints line numbers followed by the lines.
The second sed joins each number with its corresponding line and replaces the newline with a space.
Sometimes you want to make complex changes but only after a pattern has been matched. For instance, changing the format of all lines after a certain marker:
sed '/^START$/,$s/foo/bar/g' file.txt
/^START$/,$ limits the substitution range to all lines from the line that says “START” to the end.
s/foo/bar/g applies globally on those lines.
For working with JSON-like structures, you might want to collapse multiple lines into one:
sed ':a;N;$!ba;s/\n/ /g' file.json
:a marks a label.
N appends the next line.
$!ba repeats this process until the last line.
The s/\n/ /g replaces all newlines with spaces.
These examples show that sed can serve as a mini text processor, capable of restructuring, sanitizing, and formatting content in countless ways. While sed has limitations (especially with deeply nested or hierarchical data), for linear and pattern-based tasks, it’s fast, scriptable, and available out-of-the-box on Debian 12.
AIrticles is a blog containing posts written 100% with AI. They haven’t been vetted by a human. The purpose of the site is to act as a personal resource which can be used for reading enjoyment (e.g., posts on topics that interest me), or as an aide in doing things (e.g., how-tos). Posting these articles online means I can access them anywhere. You are welcome to read them too, but just remember they are unvetted AI outputs, so they may not be accurate. By continuing to access this page you acknowledge this!
As you continue to explore sed on Debian 12, you’ll find it remarkably capable of solving complex text manipulation tasks with concise commands. This follow-up provides deeper examples that demonstrate sed’s flexibility, including pattern-based logic, conditional editing, and multi-line operations.
Let’s begin with conditional deletion. Suppose you want to delete lines that contain “debug” unless they also contain “keep”. You can achieve this with:
sed '/debug/ { /keep/!d }' file.txt
This breaks down as follows:
/debug/ identifies the lines to examine.
{ /keep/!d } applies a command block:
/keep/! is a negated match—meaning lines not containing “keep”.
d deletes those lines.
Next, to change all occurrences of multiple words to different values, sed can use sequential commands:
sed -e 's/blue/green/g' -e 's/cat/dog/g' file.txt
Each -e provides a separate editing rule. This is useful when transforming various words in one pass without chaining multiple sed invocations.
To remove duplicate lines while preserving order, you can use a trick with sed and its hold space:
sed -n '/./{H;g;/^\(.*\n\)\(.*\n\)*\2$/!p}' file.txt
This is a more complex example. While sed is not designed for deduplication, this hack works for small files. It stores lines in the hold buffer and only prints them if they haven’t already appeared. For robust deduplication, however, awk or sort -u is usually better.
For matching patterns across line boundaries, standard sed falls short, since it processes one line at a time. But GNU sed supports the N command to include the next line in pattern space. For example, to replace two consecutive lines that say:
Name: John
Age: 30
with a single line:
John (30)
you could use:
sed -n 'N;s/Name: \(.*\)\nAge: \(.*\)/\1 (\2)/p' file.txt
Here’s how it works:
-n suppresses automatic printing.
N appends the next line to the pattern space.
The s command uses regex groups:
\(.*\) captures the name and age.
\n matches the newline between lines.
\1 (\2) restructures the data.
p prints the result.
You can also change the case of text using GNU sed with \L, \U, and \E. To lowercase the word “Title”:
sed 's/Title/\L&/' file.txt
\L begins lowercase mode.
& represents the matched text.
To uppercase a whole match, use \U instead.
Sometimes you’ll want to replace only the second or third match on a line. sed supports addressing individual matches with an extra number. For example:
sed 's/foo/bar/2' file.txt
Only the second occurrence of “foo” on each line is changed.
Finally, to prefix all non-empty lines with a character like “>”:
sed '/./s/^/> /' file.txt
/./ matches non-empty lines.
s/^/> / adds a prefix to the start of each matched line.
These advanced examples show how sed can adapt to complex needs, whether modifying structured data, filtering based on content, or rearranging lines. Mastery of sed on Debian 12 can significantly boost your efficiency in shell scripting, log analysis, and system administration tasks.
AIrticles is a blog containing posts written 100% with AI. They haven’t been vetted by a human. The purpose of the site is to act as a personal resource which can be used for reading enjoyment (e.g., posts on topics that interest me), or as an aide in doing things (e.g., how-tos). Posting these articles online means I can access them anywhere. You are welcome to read them too, but just remember they are unvetted AI outputs, so they may not be accurate. By continuing to access this page you acknowledge this!
Building on the basics, it becomes clear that sed is more than just a simple search-and-replace tool. Its true power lies in how it handles streams of text with pattern-matching precision. On Debian 12, sed is often used in shell scripts or piped from other commands like grep or cat. In this article, we’ll look at additional examples to deepen your understanding of what sed can do.
Let’s begin with line-specific edits. If you want to change text only on a specific line number, you can prefix your command with the line number. For example, to replace the word “apple” with “orange” only on line 2:
sed '2s/apple/orange/' file.txt
This will leave other instances of “apple” on other lines unchanged. You can also apply changes to a range of lines:
sed '5,10s/foo/bar/g' file.txt
This substitutes all occurrences of “foo” with “bar” from lines 5 through 10.
Another useful feature is inserting or appending lines. To insert a line before a specific pattern, use the i command:
sed '/^Title:/i\Author: Unknown' file.txt
This adds the line “Author: Unknown” before every line that starts with “Title:”. Similarly, to append a line after a pattern, use a:
sed '/^Title:/a\Published: 2025' file.txt
Next, let’s look at removing or replacing multiple words using alternation. To replace “cat” or “dog” with “animal”:
sed 's/\b\(cat\|dog\)\b/animal/g' file.txt
Explanation:
\b is a word boundary anchor.
\(cat\|dog\) uses escaped parentheses to group options, and \| acts like OR.
g makes it global for each line.
Let’s say you want to swap the positions of two words. If a line contains “first second” and you want to change it to “second first”, use:
sed 's/^\([a-zA-Z]\+\) \([a-zA-Z]\+\)$/\2 \1/' file.txt
Breaking that down:
^\([a-zA-Z]\+\) captures the first word.
\([a-zA-Z]\+\)$ captures the second word.
\2 \1 swaps their order in the replacement.
\+ matches one or more letters, and the brackets capture the groups.
For substitutions that include slashes, use a different delimiter to avoid escaping them. For instance, to replace a path like /home/user with /mnt/backup, use:
sed 's|/home/user|/mnt/backup|g' file.txt
Here, | is used instead of / to reduce clutter and avoid unnecessary backslashes.
You can also remove trailing whitespace from lines with:
sed 's/[ \t]*$//' file.txt
This matches any number of spaces or tabs at the end of a line ([ \t]*$) and replaces them with nothing.
For more dynamic changes, sed can use shell variables:
word="apple"
sed "s/$word/fruit/" file.txt
Double quotes allow the variable to expand, making the substitution flexible in scripts.
Through these examples, it’s clear that sed is not just useful for quick edits—it’s a scripting powerhouse for automating text transformations with surgical precision. When combined with other tools in the Unix philosophy, sed is an essential part of any Debian user’s toolkit.
AIrticles is a blog containing posts written 100% with AI. They haven’t been vetted by a human. The purpose of the site is to act as a personal resource which can be used for reading enjoyment (e.g., posts on topics that interest me), or as an aide in doing things (e.g., how-tos). Posting these articles online means I can access them anywhere. You are welcome to read them too, but just remember they are unvetted AI outputs, so they may not be accurate. By continuing to access this page you acknowledge this!
Sed, short for stream editor, is a powerful tool used on the command line for parsing and transforming text. It is particularly useful for batch-editing files, filtering text in pipelines, and making automated replacements. Debian 12 includes sed by default as part of its core utilities, making it readily available to any user comfortable working from a terminal.
At its core, sed processes input line by line, applying the commands given to it. The most common use case is substitution, which uses the s command. A basic syntax looks like this:
sed 's/old/new/' file.txt
This command replaces the first occurrence of “old” with “new” on each line of file.txt. Breaking it down:
's/old/new/': This is the substitution command.
s stands for substitute.
/ is the delimiter separating the pattern from the replacement.
old is the regular expression pattern to match.
new is the string to insert in its place.
file.txt is the file being processed.
By default, sed prints the modified output to the terminal rather than modifying the file in place. To update the file directly, you can use the -i flag:
sed -i 's/old/new/' file.txt
This tells sed to edit the file in place. It’s often wise to make a backup first. You can do that with:
sed -i.bak 's/old/new/' file.txt
This creates a backup named file.txt.bak before modifying the original.
Now let’s consider an example using a regular expression. Suppose you want to replace any number with the word “number”:
sed 's/[0-9]\+/number/g' file.txt
Here’s what’s happening:
[0-9] matches any single digit.
\+ matches one or more of the preceding pattern. This is a common POSIX-style way of expressing repetition.
Together, [0-9]\+ matches any whole number.
g at the end stands for global, meaning replace all matches on each line, not just the first.
If you want to delete lines that contain a certain pattern, use the d command:
sed '/^#/d' file.txt
This deletes all lines that start with a #—commonly used to strip out comments in configuration files.
/^#/: A regular expression that matches any line beginning with #.
^ anchors the match to the start of the line.
d tells sed to delete those matching lines.
Another helpful trick is printing only lines that match a pattern. For example:
sed -n '/error/p' file.txt
-n suppresses automatic printing of lines.
/error/ matches any line containing the word “error”.
p tells sed to print lines matching the pattern.
With sed, you can chain multiple commands. For example, to replace tabs with spaces and delete empty lines:
sed -e 's/\t/ /g' -e '/^$/d' file.txt
-e allows multiple expressions.
\t matches a tab character.
is four spaces, used as the replacement.
/^$/d deletes empty lines—^$ matches lines with no content.
While sed can appear cryptic at first, mastering its basic syntax opens the door to efficient and powerful text processing, especially in shell scripts or when working with logs and configuration files. On Debian 12, it’s a tool that can save time and avoid repetitive manual edits.
AIrticles is a blog containing posts written 100% with AI. They haven’t been vetted by a human. The purpose of the site is to act as a personal resource which can be used for reading enjoyment (e.g., posts on topics that interest me), or as an aide in doing things (e.g., how-tos). Posting these articles online means I can access them anywhere. You are welcome to read them too, but just remember they are unvetted AI outputs, so they may not be accurate. By continuing to access this page you acknowledge this!
Colour swapping in Krita can range from quick adjustments to careful, multi layered edits. Artists who want to replace a colour, shift the overall palette, or experiment with alternatives can choose from several methods depending on how precise or flexible they want the process to be. Below are step by step instructions for commonly used approaches that cover simple flat colour changes, selective adjustments, and advanced recolouring using layers. The goal is to make each method clear enough that you can follow it without prior experience, yet flexible enough to handle different styles of artwork.
Using the Colour Replace Tool
This method is helpful when you want to directly replace one specific colour with another. It works best for flat or clearly separated colours.
Open your document in Krita and select the Colour Replace tool.
Use the tool options panel to choose the source colour. You can click the eyedropper icon and select the colour directly from your canvas.
Choose the target colour by clicking the replacement colour swatch.
Adjust the threshold or tolerance slider. A low value means Krita will only replace pixels very close to the source colour. A higher value allows similar colours to be replaced as well.
Click and drag across the area you want to affect. Krita will immediately change the selected colour on the canvas.
If the result affects too many pixels or too few, undo and adjust the tolerance until you achieve a clean and accurate swap.
Continue applying the tool to additional areas if the colour appears in more than one part of your artwork.
This approach is fast but not always the most natural looking for textured paintings or images with complex shading.
Using Select by Color and Adjustment Filters
This method offers more control because you can preview the areas selected and apply finer adjustments. It works well for both illustrations and paintings.
Select the “Select by Color” tool from the selection tools list.
Click on the colour in your artwork that you want to modify. Krita will automatically select every pixel that matches or closely resembles that colour.
Use the tool options panel to adjust the fuzziness or threshold. Increasing this value broadens the selection to include similar hues.
Once satisfied with the selection, go to the Adjustments menu and choose Hue/Saturation.
In the adjustment dialog, move the Hue slider to shift the selected colour toward a new value. Saturation and Lightness can also be adjusted if needed.
Watch how the colour changes in real time and fine tune until you reach the desired look.
Click OK to apply the changes.
Deselect the area when you are finished.
This method preserves texture and shading because it edits only the hue and saturation instead of overwriting the pixel content.
Recolouring with a New Layer and Blending Modes
Layer based colour alteration is considered one of the safest and most flexible approaches. Instead of changing the original pixels, you add a new layer and paint the new colour over the target area. Krita then blends it with the original shading.
Add a new paint layer above the artwork.
Set the layer’s blending mode to “Color”. This ensures that the hues you paint will affect only colour components, not the lightness or texture.
Select a brush of your choice. A soft round brush works well for smooth transitions.
Choose the colour you want to apply.
Paint directly over the areas you want to recolour. As you paint, you will notice the underlying shading remains visible.
If the effect is too strong, reduce the opacity of the layer to soften the recolouring.
If the effect looks uneven, switch to an eraser and clean up the edges.
When satisfied, you can merge the layer or keep it separate for future adjustments.
This technique is very helpful for character art, environment design, or any artwork where you want to test multiple palettes without damaging previous work.
Recolouring with Overlay or Soft Light Modes
Sometimes you want stronger or more dramatic colour changes. Using a layer mode like Overlay or Soft Light can increase contrast while applying colour.
Create a new paint layer above the artwork.
Change the layer mode to “Overlay” or “Soft Light”.
Pick the colour you want to apply and a soft brush.
Paint the colour across the target area.
Adjust the layer opacity to control the intensity.
If the result is too bright or too dark, try switching between Overlay and Soft Light to see which gives the desired effect.
Clean up edges with the eraser tool if needed.
This method is especially useful for adding warmth, cooling tones, or enhancing atmosphere without losing the artistic character of the original painting.
Using Filter Masks for Non Destructive Adjustments
Filter masks allow you to apply colour changes to a specific part of a layer while keeping the original pixels intact. This is ideal when experimenting, because you can toggle the filter on and off at any time.
Select the layer that contains the colours you want to adjust.
Right click the layer and choose Add -> Filter Mask.
In the filter list, choose Hue/Saturation.
Adjust the Hue slider to shift the colour range. You can also modify Saturation and Lightness if required.
Click OK to confirm.
The filter mask now appears linked to your layer. Select the mask and paint with black to hide the effect in certain areas or white to reveal it.
If you want to change the adjustment later, double click the mask and reopen the settings.
This approach is excellent for fine tuning colour variations on clothing, backgrounds, or props without repainting anything.
Using Selections with Masks for Detailed Recolouring
If you need precision with curved shapes or complex regions, combining a selection with a mask can be the most accurate method.
Use a selection tool such as the Freehand Selection or Polygonal Selection tool to outline the area you want to recolour.
Once selected, add a new layer above the artwork.
Create a mask on the new layer. The mask will automatically match the selection.
Set the new layer’s blending mode to “Color”.
Paint inside the masked area using your chosen colour.
If you make errors, edit the mask directly by painting black to hide colour or white to reveal it.
When finished, deselect the area.
This method gives detailed control, especially when dealing with hair, clothing folds, or objects with sharp outlines.
Global Colour Shifts for Entire Images
Sometimes colour swapping involves adjusting the overall palette instead of specific areas.
Select the topmost layer or create a new filter mask on a group that contains the entire artwork.
Apply a Hue/Saturation filter.
Move the Hue slider until you reach the overall tone you want.
Adjust Saturation and Lightness if needed.
Confirm the change.
This method is often used when unifying colours or testing different moods for a scene.
Choosing the Right Method
Each recolouring method serves a different purpose. The Colour Replace tool works well for simple images but may show rough transitions on textured paintings. Selection based adjustments provide accuracy and allow previewing changes before committing. Layer based recolouring gives the best balance of flexibility and non destructive editing. Filter masks provide control and reversibility. Blending modes like Overlay or Soft Light bring atmosphere and dramatic shifts when needed.
Good results come from experimenting with these tools until you understand how each affects your style of art. Many artists mix methods. For example, you might start with a colour selection, apply a hue shift for the base change, and then add a colour layer to refine specific tones. The more you practice these steps, the more natural colour swapping becomes.
Colour alteration in Krita is not only a corrective process but also a creative one. Once you become comfortable with the tools, you can use them for exploration, testing different palettes, or preparing alternate versions of your work. Whether you are developing character designs, adjusting environmental lighting, or correcting colour choices, Krita provides a range of methods that support both precision and artistic freedom.
AIrticles is a blog containing posts written 100% with AI. They haven’t been vetted by a human. The purpose of the site is to act as a personal resource which can be used for reading enjoyment (e.g., posts on topics that interest me), or as an aide in doing things (e.g., how-tos). Posting these articles online means I can access them anywhere. You are welcome to read them too, but just remember they are unvetted AI outputs, so they may not be accurate. By continuing to access this page you acknowledge this!