shantanuo
shantanuo

Reputation: 32306

restricting sed command

I have a variables that needs to be modified so that minutes %M is added. I know the sed command and it is working as expected.

# cat mysed.txt 
myfirstfile="comany$mydb`date +'%d-%b-%Y-%H'`.sql"

# sed -i 's/\%H/\%H-\%M/' mysed.txt
# cat mysed.txt 
myfirstfile="company$mydb`date +'%d-%b-%Y-%H-%M'`.sql"

But if I run the same sed command again, it will add %M again as follows.

# sed -i 's/\%H/\%H-\%M/' mysed.txt

# cat mysed.txt 
myfirstfile="company$mydb`date +'%d-%b-%Y-%H-%M-%M'`.sql"

I need a sed command that should add the minutes %M only once even if sed command is executed twice (by mistake)

Upvotes: 1

Views: 75

Answers (3)

Shirish
Shirish

Reputation: 47

I believe below command will work fine.Please replace test.dat file with your file name.

cat test.dat|sed "s/\%H\'/\%H\-\%M\'/" > test.dat

Without cat command

sed -i "s/\%H\'/\%H\-\%M\'/" test.dat >  test.dat

Cheers!

Upvotes: 0

Thor
Thor

Reputation: 47099

Test if it is present before substituting:

sed '/%H-%M/! s/%H/%H-%M/' mysed.txt

Btw. % does not need to be escaped.

Upvotes: 0

placeybordeaux
placeybordeaux

Reputation: 2216

# sed -i "s/%H'/%H-%M'/" mysed.txt

This should work. This way it will only do the replacement if there is a quote mark next to the %H.

Upvotes: 3

Related Questions