≡ Menu

sed find and replace

I'm using the date +'%D_%T' to store Unix system date and time in a shell variable called $_now:

_now="$(date +'%D_%T')"
echo $_now

Outputs:
01/20/12_16:10:42

I'd like to replace / and : with _. I'm aware of the following sed command:

sed 's/\//_/g
> s/:/_/g' < <<"$_now"

Outputs:
01_20_12_16_14_09

How do I specify two pattern within the same sed command to replace | and : with _ so that I can get output as 01_20_12_16_10_42?
[click to continue…]

sed Case Insensitive Search Matching

Q. How do I perform a case-insensitive search using sed under UNIX / Linux? I'd like to match all combination of word - foo, FOO, FoO and so on while replacing or performing other operations.
[click to continue…]

sed: Remove All Digits / Input From Input

Q. How do I remove all digits or number from my text file or input using sed command?
[click to continue…]

Q. How do I find and replace character codes ( control-codes or nonprintable characters ) such as ctrl+a using sed command under UNIX like operating systems?
[click to continue…]

Q. I need to delete all empty lines but could not figure out sed command for the same? How do I delete all empty lines with sed?

A. sed is a stream editor and perfect for these kind of work.

You need to use d command under sed which is act as the delete function.

Sed Delete Empty Line Syntax

sed '/^$/d' <input-file>
echo LINE | sed '/^$/d'
echo $VAR | sed '/^$/d'

So to delete all empty lines from a file called /tmp/data.txt, enter:
$ sed '/^$/d' /tmp/data.txt
To store output to another file use redirection operator:
$ sed '/^$/d' /tmp/data.txt > /tmp/output.txt

Deleting a line that matches a pattern

You can also match a word or a pattern to delete. For example
$ cat data.txt
Output:

This is a test
Linux rulez
Windows sucks
Redhat is good server disro

To delete all lines that contain a 'Windows' word, enter:
$ sed '/Windows/d' /tmp/data.txt > /tmp/output.data.txt
GNU Sed support -i option to edit files in place:
$ sed -i '/Windows/d' /tmp/data.txt

See more sed examples:

=> Delete text or paragraph between two sections using sed

Updated for accuracy.