Reputation: 6365
I have a log file like this:
20141107 14:15:02;10.0.0.5;/home/it/17066.txt;0
20141107 14:15:32;10.0.0.5;/home/it/17076.txt;0
20141107 14:16:15;10.0.0.5;/home/it/17086.txt;0
...
My bash script parsing big log file and create new small log files. Script check small log file and if does not exist, create:
if [ ! -f "$path/$name" ]; then
mkdir -p "$path"
touch "$path/$name"
echo "$year$month$day $time;$ip;$file;$size" >> "$path/$name"
fi
If the log file is exist, I want to write into that file. I try this:
if [ ! -f "$path/$name" ]; then
mkdir -p "$path"
touch "$path/$name"
echo "$year$month$day $time;$ip;$file;$size" >> "$path/$name"
else
echo "$year$month$day $time;$ip;$file;$size" >> "$path/$name"
fi
It's working if file exist or not. But writing same lines in log file:
20141107 14:15:02;10.0.0.5;/home/it/17066.txt;0
20141107 14:15:32;10.0.0.5;/home/it/17076.txt;0
20141107 14:16:15;10.0.0.5;/home/it/17086.txt;0
20141107 14:15:02;10.0.0.5;/home/it/17066.txt;0
20141107 14:15:32;10.0.0.5;/home/it/17076.txt;0
20141107 14:16:15;10.0.0.5;/home/it/17086.txt;0
...
I need to do if line does exist in log file, write. If line exist in log file, skip.
How can I do?
Upvotes: 0
Views: 77
Reputation: 249113
str="$year$month$day $time;$ip;$file;$size"
if ! grep -q "^$str$" "$path/$name"; then
echo "$year$month$day $time;$ip;$file;$size" >> "$path/$name"
fi
Note that this is not efficient if the output file becomes large.
Upvotes: 1
Reputation: 20254
Why not just do this:
if [ ! -f "$path/$name" ]; then
mkdir -p "$path"
touch "$path/$name"
fi
echo "$year$month$day $time;$ip;$file;$size" >> "$path/$name"
Upvotes: 0