如何将文件内容追加到另一文件?脚本实现遇阻求助
实现文件内容追加的脚本示例
根据你的需求,以下是几种常用脚本语言的实现方案,完全匹配你给出的逻辑:
Bash 脚本实现
Bash里用>>符号实现文件追加,结合条件判断直接调用cat命令即可:
#!/bin/bash engineer="target_engineer" # 替换成你的实际变量值 if [ $x -eq 1 ]; then cat ./machines/x.txt >> ./$engineer.txt fi if [ $y -eq 1 ]; then cat ./machines/y.txt >> ./$engineer.txt fi if [ $z -eq 1 ]; then cat ./machines/z.txt >> ./$engineer.txt fi
- 核心:
>>是追加模式的重定向符,会把内容加到目标文件末尾,不会覆盖原有内容;cat命令用来读取源文件内容并输出到目标文件。 - 注意:变量
x/y/z需要提前定义赋值,比如x=1。
Perl 脚本实现
如果你的脚本是Perl风格,可通过文件句柄操作实现追加:
#!/usr/bin/perl my $engineer = "target_engineer"; # 替换实际值 my $target_file = "./$engineer.txt"; # 打开目标文件(追加模式) open my $out_fh, '>>', $target_file or die "无法打开目标文件: $!"; if ($x == 1) { open my $in_fh, '<', './machines/x.txt' or die "无法读取x.txt: $!"; print $out_fh $_ while <$in_fh>; close $in_fh; } if ($y == 1) { open my $in_fh, '<', './machines/y.txt' or die "无法读取y.txt: $!"; print $out_fh $_ while <$in_fh>; close $in_fh; } if ($z == 1) { open my $in_fh, '<', './machines/z.txt' or die "无法读取z.txt: $!"; print $out_fh $_ while <$in_fh>; close $in_fh; } close $out_fh;
- 核心:打开目标文件时用
>>模式,确保内容追加;逐行读取源文件内容并写入目标文件。
Python 脚本实现
Python中通过open()函数的mode='a'参数实现追加:
engineer = "target_engineer" target_path = f"./{engineer}.txt" if x == 1: with open("./machines/x.txt", 'r') as src_f, open(target_path, 'a') as dest_f: dest_f.write(src_f.read()) if y == 1: with open("./machines/y.txt", 'r') as src_f, open(target_path, 'a') as dest_f: dest_f.write(src_f.read()) if z == 1: with open("./machines/z.txt", 'r') as src_f, open(target_path, 'a') as dest_f: dest_f.write(src_f.read())
- 核心:
mode='a'表示以追加模式打开文件;with语句自动处理文件的打开和关闭,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Pete G
相关产品推荐
相关产品推荐

