Reputation: 1
I have got a text file containing some data which is separated by a dashed line. I need to store each days data in a separate file with <filename>_yyyymmdd
.
Input_file:
01-01-2017
Some text data
--------------------------
10-10-2017
Some text data
--------------------------
So far I have tried is: Have some errors in the code.
while read line; do
if [[ $line =~ ^[0-9]{2}-[0-9]{2}-[0-9]{4}$ ]] ; then; fi
done > Input_file
I am trying to read the date format from the file and creating a new file and appending data format to it.
Upvotes: 0
Views: 831
Reputation: 785128
If you are looking for a bash
solution then use:
#!/bin/bash
f="${1?needs a filename}"
while IFS= read -r line; do
[[ $line =~ ^([0-9]{2})-([0-9]{2})-([0-9]{4})$ ]] &&
fn="${f}_${BASH_REMATCH[3]}${BASH_REMATCH[2]}${BASH_REMATCH[1]}"
[[ $line =~ ^-+$ ]] || echo "$line" >> "$fn"
done < "$f"
Otherwise this slightly verbose awk
will also work:
awk '/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/{
split($0, a, "-"); if (fn) close(fn); fn = FILENAME "_" a[3] a[2] a[1]}
!/^-+$/{print $0 > fn}' filename
Upvotes: 1