1

I have a file which looks like this:

**********************************
Some notes are here
Year Month Day Hour Minute Second
. . . . . . . . . . . . . . . . .

Undertneath this, I would like to have dates appear using the following code

#!/bin/bash
for  timestamp in (1262300400..1264978800..600)
do
date -d @"$timestamp" '+%Y %m %d %H %M %S';
done | grep -Ev '[15]0 00$' > file.txt

If you want to know how I got this code, please read question Range of dates with minutes The difficulty in this question is the last part "> file.txt". The current code overwrites what is already in the file.txt. I want this loop to print the dates underneath the notes of the file 'file.txt', so for it to start writing at lets say the 5th line or something.

So the desired output would be

**********************************
Some notes are here
Year Month Day Hour Minute Second
. . . . . . . . . . . . . . . . .
2010 01 01 00 00 00
2010 01 01 00 20 00
2010 01 01 00 30 00
2010 01 01 00 40 00
2010 01 01 01 00 00 
  • 2
    Use >> instead of > – Inian May 28 '19 at 12:07
  • Are there other existing lines below the notes that should be preserved (and appear after the inserted dates)? Perhaps a realistic example of the desired output would help. – Jeff Schaller May 28 '19 at 12:13
  • @Jeff Schaller no there is nothing undertneath it I just want dates underneath it – Jellyse May 28 '19 at 12:14
4

Redirecting using > would create the output file that you redirect to, or, if it already exists, would truncate it to zero size. Any writes to the file would start at the beginning of the file and data would be written sequentially. This is not what you want to do.

Redirecting using >> would create the output file, or, if it already exists, would not truncate it. Any writes to the file would be happening at the end of the file. This is what you want to do.

Additionally, you have a syntax error in the code. I'm assuming you wanted to use a brace expansion in the loop:

#!/bin/bash
for  timestamp in {1262300400..1264978800..600}; do
    date -d @"$timestamp" '+%Y %m %d %H %M %S'
done | grep -v '[15]0 00$' >>file.txt

Also, this is an extremely slow loop, calling date a large number of times (4465 times, to be exact; the number of ten-minute time segments in a 31 day month). To speed things up, use the fact that GNU date can read from a file (here, we provide the timestamps on standard input, which date reads using -f -):

#!/bin/bash
printf '@%s\n' {1262300400..1264978800..600} |
date -f - '+%Y %m %d %H %M %S' |
grep -v '[15]0 00$' >>file.txt

This would run in a second or less.

I've also removed the -E from the invocation of grep as you don't use an extended regular expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.