如何在bash中为不同目录下的多个variables_file.txt添加新变量及空行?
Bash批量修改所有variables_file.txt文件的方法
问题描述
现有目录结构如下:
directory_1 variables_file.txt bash_script.bash directory_2 variables_file.txt bash_script.bash sub_directory_1 variables_file.txt bash_script.bash directory_3 variables_file.txt bash_script.bash
每个variables_file.txt的内容示例为:
export src_table_name='test_abc_table' export starttime="$(date --utc "+%Y-%m-%d %T")" export tgt_table_name='test_xyz_table'
需要为所有位置的variables_file.txt文件末尾添加一行export abc_test_value='test_command',并在该行后添加一个空行,修改后内容如下:
export src_table_name='test_abc_table' export starttime="$(date --utc "+%Y-%m-%d %T")" export tgt_table_name='test_xyz_table' export abc_test_value='test_command'
解决方案
可以用find命令结合输出工具批量完成,推荐两种实用方法:
方法1:find + echo分两步追加
find . -name "variables_file.txt" -exec sh -c 'echo "export abc_test_value='\''test_command'\''" >> "$1"; echo "" >> "$1"' _ {} \;
- 解释:
find . -name "variables_file.txt":递归查找当前目录下所有目标文件;-exec sh -c '...' _ {} \;:对每个找到的文件执行后续脚本,$1代表当前遍历到的文件路径;- 第一条
echo追加指定变量行,第二条echo追加空行。
方法2:find + printf一次性输出两行
find . -name "variables_file.txt" -exec printf "export abc_test_value='test_command'\n\n" >> {} \;
- 解释:
printf的\n\n会直接输出变量行加一个空行,一次性完成追加操作,写法更简洁。
前置检查建议
执行修改前,可先运行以下命令确认会操作哪些文件,避免误改:
find . -name "variables_file.txt" -print
内容的提问来源于stack exchange,提问作者nmr
相关产品推荐
相关产品推荐

