Linux / Unix: Sed Substitute Multiple Patterns [ Find & Replace ]

by Vivek Gite on January 20, 2012 · 1 comment

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?

You can use any one of the following sed substitute find and replace multiple patterns:

 
sed -e 's/Find/Replace/g' -e 's/Find/Replace/g' <<<"$var"
sed -e 's/Find/Replace/g' -e 's/Find/Replace/g' < inputFile > outputFile
out=$(sed -e 's/Find/Replace/g' -e 's/Find/Replace/g' <<<"$var")
 

OR

 
sed 's/Find/Replace/g;s/Find/Replace/g' <<<"$var"
sed -e 's/Find/Replace/g;s/Find/Replace/g' <<<"$var"
sed -e 's/Find/Replace/g;s/Find/Replace/g' < inputFile > outputFile
out=$(sed -e 's/Find/Replace/g;s/Find/Replace/g' <<<"$var")
 

Examples: Find And Replace Sed Substitute Using a Singe Command Line

 
_now="$(sed -e 's/\//_/g;s/:/_/g' <<<$(date +'%D_%T'))"
echo $_now
 

Sample outputs:

01_20_12_16_22_21

Here is another version:

 
_now=$(sed 's/[\/:]/_/g' <<<$(date +'%D_%T'))
echo "$_now"
 

Sample outputs:

01_20_12_16_24_42

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 1 comment… read it below or add one }

1 sylvainulg January 23, 2012

Alternatively, one could tell `date` the desired format, like date +%Y-%m-%d-%H-%M

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 11 + 13 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: