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

Posted on in Categories last updated January 20, 2012

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


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

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


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")


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:


Here is another version:

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

Sample outputs:


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

5 comment

  1. I have a not well experience with awk and sed. if any find the solution?
    I have a two variable like..
    a-fdfgh3 ##here two word in one column and may you can say in row
    $var2=a-45afd4 string1 string2 string3 string4
    a-fdfgh3 string1 string2 string3 string4
    a-hfdj3e string1 string2 string3 string4
    a-jkkl3l string1 string2 string3 string4

    i want to find $var1 data in $var2 and the output should be
    Example: a-45afd4 string1 string2 string3 string4
    a-fdfgh3 string1 string2 string3 string4

    ##rest all column row should not come

Leave a Comment