我正在尝试从每行中的Unix文件中搜索特定字符串,并错误地记录这些记录。有人可以让我如何改进我的代码,如下所示。如果您有更好的解决方案,请分享您的想法。
v_filename=$1;
v_new_file="new_file";
v_error_file="error_file";
echo "The input file name is $var1"
while read line
do
echo "Testing $line"
v_cnt_check=`grep ',' $line | wc -l`
echo "Testing $v_cnt_check"
# if [ $v_cnt_check > 2 ]; then
# echo $line >> $v_error_file
# else
# echo $line >> $v_new_file
# fi
done < $v_filename
输入:
1,2,3
1,2,3,4
1,2,3
输出:
(New file)
1,2,3
1,2,3
(Error file)
1,2,3,4
答案 0 :(得分:2)
awk -F ',' -v new_file="$v_new_file" -v err_file="$v_error_file" \
'BEGIN { OFS="," }
NF == 3 { print >new_file }
NF != 3 { print >err_file }' $v_filename
第一行设置文件名变量,并将字段分隔符设置为逗号。第二行也将输出字段分隔符设置为逗号。第三行将具有3个字段的行打印到新文件中;第四行将除3个字段以外的行打印到错误文件中。
请注意,您的代码在大文件上会非常慢,因为它每行执行两个进程。此代码只有一个进程在整个文件上运行 - 如果输入增长到数千或数百或更多行,这将非常重要。
答案 1 :(得分:0)
来自grep联机帮助页:
General Output Control
-c, --count
Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-
matching lines. (-c is specified by POSIX.)
您可以执行以下操作:
grep --count "your pattern" v_filename
获取出现次数。如果您只想要模式的行数,请将上面显示的grep替换为:
grep "your pattern" v_filename | wc -l