0

What is the best way to change a character in a string in shell script ?

I have the following variable:

A="2017-03-16 18:00:00"

I would like to change it for "2017-03-16 18:00:01" (adding +1)

2 Answers 2

2

You can use the date command to add 1 second to a specific date:

$ date -d "2017-03-16 18:00:00+1 seconds"
Thu Mar 16 13:00:01 EDT 2017

(Note that this converted to local timezone EST)

Incorporated into your script, that would be:

#!/bin/sh 

A="2017-03-16 18:00:00"
date -d "$A+1 seconds"
Sign up to request clarification or add additional context in comments.

4 Comments

I would like to do something like that A[18]=1 like in C, for instance.
I was able to accomplish that like that echo $A | sed s/./1/19.
That isn't the question you asked.
This was not what I asked, but I found out your solution was better. Thank you!
0

If you want to Change character of a string in shell script as mentionned in your title, you can use parameter expansion:

$ A="2017-03-16 18:00:00"
$ echo ${A%0}1
2017-03-16 18:00:01

If you want to add 1 second to a date, then Hunter McMillen's answer does the job.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.