%====================
% 本代码用于将bibtex的.bib文件里面的条目顺序按照正文.tex文件\cite{}引用的顺序排序
% 效果为:bib文件的条目顺序与正文参考文献的顺序一致,目的是为了方便bib文件里面的条目管理
% 使用顺序为:先按照往常的习惯正常正文cite bib文件里面的内容,最后cite完毕,再进行
% 条目顺序的统一,就为了bib文件里面的顺序好看,没别的作用
% Author: JIANG Qian
% date: 2022-11-11
%====================
%% 读取包含引用\cite{}字段的.tex文件以及参考文献条目文件.bib
clc
file_path = 'E:\Course_Data\SJTUThesis\';
file_name = {'intro.tex','math_and_citations.tex','floats.tex','summary.tex'};
tex_words = [];
for i = 1:length(file_name)
tex_id = fopen([file_path 'contents\' file_name{i}],'r');
tex_words = [tex_words fscanf(tex_id, '%s')];
fclose(tex_id);
end
bib_id = fopen([file_path 'bibdata\' 'thesis.bib'],'r');
bib_words = fscanf(bib_id, '%c');
fclose(bib_id);
%% 读取bib文件里的条目
where_at = strfind( bib_words, '@');
bib_key_list = [];
bib_content_list = [];
for i = 1:length(where_at)
if i == length(where_at)
bib_content = bib_words( where_at(i):end );
else
bib_content = bib_words( where_at(i): (where_at(i+1) - 1) );
end
where_brace = find( bib_content == '{');
where_comma = find( bib_content == ',');
bib_key = bib_content( where_brace(1)+1 : where_comma(1)-1 );
bib_key_list = [bib_key_list string(bib_key)];
bib_content_list = [bib_content_list string(bib_content)];
end
%% 读取正文tex里的cite顺序
where_cite = strfind( tex_words, '\cite{');
cite_content_list = [];
for i = 1:length(where_cite)
tex_piece = tex_words( where_cite(i):end );
where_reverse_brace = strfind( tex_piece, '}');
cite_content = tex_piece( 1+length('\cite{') : where_reverse_brace(1)-1 );
if isempty(cite_content)
continue;
end
where_comma = strfind(cite_content, ',');
% 判断当前引用括号里有没有逗号分隔的多个引用 key
if isempty( where_comma )
found_a_cite = cite_content;
if i == 1
cite_content_list = [cite_content_list string(found_a_cite)];
elseif ~contains(cite_content_list, found_a_cite)
cite_content_list = [cite_content_list string(found_a_cite)];
end
else
where_comma = [0 where_comma];
for j = 1:length( where_comma )
if j == length( where_comma )
found_a_cite = cite_content( where_comma(j)+1:end);
else
found_a_cite = cite_content( where_comma(j)+1 : where_comma(j+1)-1 );
end
if i == 1 && j == 1
cite_content_list = [cite_content_list string(found_a_cite)];
elseif ~contains(cite_content_list, found_a_cite)
cite_content_list = [cite_content_list string(found_a_cite)];
end
end
end
end
%% 生成对应tex cite顺序的bib文件
bib_order_id = fopen( 'bib_ordered.bib', 'w' );
bib_order_list = [];
for i = 1:length(cite_content_list)
where_bib = find( bib_key_list == cite_content_list(i) );
if isempty(where_bib)
continue;
end
bib_order_list = [bib_order_list where_bib];
fprintf( bib_order_id, '%s\n', bib_content_list(where_bib));
fprintf('第%d条参考文献\n%s\n', i, bib_content_list(where_bib) );
end
bib_content_list(bib_order_list) = [];
fprintf( bib_order_id, '%s\n', bib_content_list);
fclose(bib_order_id);
bib里面的参考文献和正文参考文献顺序一致
于 2022-11-11 10:18:32 首次发布