How can I update the lines of a file using bash?
I have a small script to log disk usage like:
#!/bin/bash
date=$(date +"%d.%m.%Y")
while read -r filesystem;
do
filesys=${filesystem}
df -P | tr -d "%" | awk '$6=="'"$filesys"'" {print"'"$date"'"",",$6","$5}' >> /root/disk.csv
done < "/root/disklist"
/ root / disklist:
/
/dev/mapper/map1
/root/disk.csv:
18.05.2015, /,18 18.05.2015, /dev/mapper/map1,1
When I run this script, print a new line disk.csv. I need to see the actual data, so when I run this script, I need to update to the same line around the same date (no insert).
Not this way:
Launch - 05/18/2015 13:00
18.05.2015, /,18 18.05.2015, /dev/mapper/map1,1
Launch - 05/18/2015 15:00
18.05.2015, /,18 18.05.2015, /dev/mapper/map1,1 18.05.2015, /,19 18.05.2015, /dev/mapper/map1,5
When running the script, I need to change the old line (if the same date). How can i do this?
source to share
The getaway: you run df -P
without an argument (generate complete statistics of all your drives) so many times that you had lines in /root/disklist
.
So my goal (using recent bash) is:
disklist=(
/home
/usr
/var
)
[ -f "/root/disklist" ] && disklist=($(</root/disklist))
file="/root/disk.csv"
printf -v myDate "%(%d.%m.%Y)T" -1
sed -e "/^$myDate,/d" $file >$file.tmp
df -P "${disklist[@]}" |
sed -ne 's/^.* \([0-9]\+\)% \(.*\)$/'$myDate', \2, \1/p' >>$file.tmp
read osize < <(stat -c%s $file)
read nsize < <(stat -c%s $file.tmp)
((nsize+=${#disklist[@]}*2)) # So length of % field could become smaller
[ $nsize -ge $osize ] && mv $file.tmp $file || rm -v $file.tmp >&2
As sed -e "/^$myDate,/d" -i $file
it will be embedded edit $file
to delete all lines starting with 18.05.2015,
, before adding the corrected output df -P
.
source to share
It's not entirely clear what you want, but maybe this will help:
#!/bin/bash
df -P | awk -v date="$(date +"%d.%m.%Y")" -v OFS=',' '
NR==FNR{disk[$1 OFS $2]=$3; next}
{disk[date OFS $6]=$5+0}
END {for (key in disk) print key, disk[key]}
' FS=',' /root/disk.csv FS=' ' - > tmp && mv tmp /root/disk.csv
source to share