DEV Community

Dmitry Romanoff
Dmitry Romanoff

Posted on

Write bash script to append the file with 100 more similar records.

Given the file records.txt:

One | 1 | 2021-01-01 01:01:01 
Two | 2 | 2022-02-02 02:02:02
Three | 3 | 2023-03-03 03:03:03
Four | 4 | 2024-04-04 04:04:04
Five | 5 | 2025-05-05 05:05:05
Enter fullscreen mode Exit fullscreen mode

Here's an example bash script to append 100 more records in the same format as the given file:

#!/bin/bash

for (( i=6; i<=105; i++ ))
do
    # Generate random number between 1-5
    num=$(( RANDOM % 5 + 1 ))

    # Generate random date between 2026-01-01 to 2030-12-31
    d=$(shuf -i 17897-19100 -n 1)
    date=$(date -d "1900-01-01 + $d days" "+%Y-%m-%d")

    # Generate random time between 00:00:00 to 23:59:59
    time=$(date -d@$(( RANDOM % 86400 )) -u "+%T")

    # Append record to file
    echo "Record$i | $num | $date $time" >> records.txt
done
Enter fullscreen mode Exit fullscreen mode

This script generates 100 new records in the same format as the given file, with the record number starting from 6 and increasing up to 105. The script uses the shuf command to generate a random number of days between 17897 and 19100 (which correspond to the dates between 2026-01-01 and 2030-12-31) and then formats it as a date using the date command. It also generates a random time between 00:00:00 to 23:59:59 using the date command. Finally, the script appends the new record to the end of the file records.txt.

dmi@dmi-laptop:~$ cat records.txt 
One | 1 | 2021-01-01 01:01:01 
Two | 2 | 2022-02-02 02:02:02
Three | 3 | 2023-03-03 03:03:03
Four | 4 | 2024-04-04 04:04:04
Five | 5 | 2025-05-05 05:05:05
Record6 | 3 | 1949-06-24 02:19:06
Record7 | 4 | 1951-09-06 08:01:10
Record8 | 3 | 1950-09-17 07:20:10
...
Record103 | 4 | 1950-06-04 03:28:20
Record104 | 4 | 1950-12-23 07:16:30
Record105 | 1 | 1949-04-18 05:15:32
dmi@dmi-laptop:~$
Enter fullscreen mode Exit fullscreen mode

Top comments (0)