Make changes to multiple files simultaneously?

I need to add one line of code to 100 files, is there any way I can modify all of them at once (without changing them individually?)
Thanks.

回答 (1 件)

dpb
dpb 2023 年 3 月 6 日
編集済み: dpb 2023 年 3 月 7 日

0 投票

Notepad++ has a feature that may work if you can make the replacement with a [regexp] expression as a substitution.
Alternatively, there are editors with batch-capable commands that can operate in batch file mode in a for...each mode on a file list.
Or, you can write a Matlab script that does the job -- if the line goes in a fixed location like at the end, it's pretty trivial if the files are either named with a well-defined name that is usable wildcard pattern or are all in a given location --
Alert -- air code, test thoroughly before destroying anything by having backups!!!
nL=100; % target line number in file
L="Your new text"; % the text to add/insert
d=dir(fullfile('yourfolder','yourfile*wildcardname.ext')); % get the list of files
for i=1:numel(d)
fn=fullfile(d(i).folder,d(i).name); % the fully-qualifie fn
F=readlines(fn); % in memory as string array
F=[F(1:nL);L;F(nL+1:end)]; % insert the line where wanted
writematrix(F,fn) % rewrite modified file
end
The above overwrites the original file, obviously you can modify the filename before writing to avoid that...

4 件のコメント

Zi
Zi 2023 年 3 月 7 日
@dpb Hi thanks for the response.
There is an error with F = F(; ; ;) line: "invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters"
I changed the semicolons with comma, got the following error:
"Error using readlines. Not enough input arguments."
Your advice on it is highly appreciated.
dpb
dpb 2023 年 3 月 7 日
編集済み: dpb 2023 年 3 月 7 日
F=[F(1:nL);L;F(nL+1:end)];
Stephen23
Stephen23 2023 年 3 月 7 日
F=readlines(fn);
dpb
dpb 2023 年 3 月 7 日
編集済み: dpb 2023 年 3 月 7 日
Thanks, @Stephen23. I started with the fullfile() in there and then realized needed it again and moved it -- but then failed to put the variable back in its place...I did say was air code... :)

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2022b

質問済み:

Zi
2023 年 3 月 6 日

編集済み:

dpb
2023 年 3 月 7 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by