Search code examples
linuxbash

add new variable and new line in many files present in different directories in bash


I have a directory structure like below in bash.

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
   

contents of variables_file.txt are below. Line numbers are for illustration only not in file

1) export src_table_name='test_abc_table'
2) export starttime="$(date --utc "+%Y-%m-%d %T")"
3) export tgt_table_name='test_xyz_table'

I want to add a new variable and a new line after the variable to all the variables_file.txt files irrespective of where they are present.

export abc_test_value='test_command'

Expected contents after adding the new variable to the variables_file.txt are below

1) export src_table_name='test_abc_table'
2) export starttime="$(date --utc "+%Y-%m-%d %T")"
3) export tgt_table_name='test_xyz_table'
4) export abc_test_value='test_command'
5) 

I am able to add manually but it is time taking to add in 100 of similar files.

Is there any other way to do this in bash.


Solution

  • Pipe a find command to a loop that appends to each of the matching files.

    find topdir -name variables_file.txt | while read -r filename; do
        cat >>"$filename" <<EOF
    export abc_test_value='test_command'
    
    EOF
    done