2

I have a file with a single line of text inside. How can I modify its content without using the vi editor?

Below is the example:

PROCESS DATE =2014-08-01

I want to increment the 2014-08-01 date to the next possible day. My idea is creating a variable. How can I do that?

1
  • Is this on Linux or some other unix variant? Commented Aug 11, 2014 at 23:22

4 Answers 4

2

You could use perl:

perl -MTime::Piece -pi -e 's/\d{4}-\d\d-\d\d/
 (Time::Piece->strptime($&,"%Y-%m-%d")+24*60*60)->date/ge' file

would increment every date in the file.

2

I would write:

increment_date() {
    local current=$(grep -oP 'PROCESS DATE =\K.+' file)
    local next=$(date -d "$current + 1 day" +%F)
    sed -i "/PROCESS DATE =/s/$current/$next/" file
}

cat file
increment_date
cat file
increment_date
cat file
PROCESS DATE =2012-02-28
PROCESS DATE =2012-02-29
PROCESS DATE =2012-03-01

This assumes the PROCESS DATE line only occurs once in the file, and it is on a line by itself.

1

It depends on how sophisticated you need this. If all you need is to change the 01 to a 02, you can use something like

sed -i 's/01/02/' file

or

perl -i -pe 's/01/02/' file

Or, to be on the safe side, do it only if the 01 is at the end of the line:

sed -i 's/01$/02/' file
perl -i -pe 's/01$/02/' file

Both of the above solutions will modify the original file because of the -i flag.

If you need to be able to take actual dates into account and, for example, increment 2014-02-28 to 2014-03-01, you need to either use a full-fledged programming language that can parse dates or play around with the date command:

$ while IFS='=' read -r text date; do 
    echo "$text=$(date -d "$date + 1 day" +%F)"; 
  done < file > new_file

The above will split input lines on =, saving the part before the = as $text and the rest as $date. Then, the $date is fed to the date command which can do fancy date manipulations like add a day and then print it out in the format you want (in this case, the format is %F which means Year-Month-Day). Note that this assumes GNU date.

The echo command prints the contents of $text and then the date incremented by one day. This will fail if you have more than one = on any line of your file.

0

My very own dateutils provide a command-line tool dadd which goes through a text file and adds something to every date found:

$ dadd -S +1d FILE
PROCESS DATE =2014-08-02

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.