Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Last active August 25, 2023 04:29
Show Gist options
  • Save mattkenefick/6ff3d3b4b17c1e9f43d0908cf830bbd2 to your computer and use it in GitHub Desktop.
Save mattkenefick/6ff3d3b4b17c1e9f43d0908cf830bbd2 to your computer and use it in GitHub Desktop.
Combine two env/ini files and remove duplicate entries

Purpose

If you're making a project where you need a base level of configs and various combinations of overrides... this merge.sh script will let you combine multiple .env or .ini files (key/value) and remove duplicates based on the key.

Usage Example

Create both files in a structure like:

    specific.env
    base.env
    merge.sh

Run sh merge.sh specific.env base.env

Results: cat merged.env

Copy and Paste Example

echo 'name=Barbara Miller
city=Brooklyn' > specific.env;

echo 'name=John Doe
city=Manhattan
state=NY
zip=10001' > base.env;

cat > merge.sh <<\EOF 
#!/bin/bash
cat $1 > tmp0
cat $2 >> tmp0
awk -F "=" '!a[$1]++' tmp0 > tmp1 && mv tmp1 merged.env && rm tmp0
EOF

chmod 0755 merge.sh;

sh merge.sh specific.env base.env;

cat merged.env;

The copy and paste example will create the two example files, the merge script, make it executable, execute it, then display the results.

Note: This will not execute properly on Windows Cmder because of the multi-line heredoc. It should work just fine in a standard terminal, Git bash, etc.

name=John Doe
city=Manhattan
state=NY
zip=10001
#!/bin/bash
cat $1 > tmp0
cat $2 >> tmp0
awk -F "=" '!a[$1]++' tmp0 > tmp1 && mv tmp1 merged.env && rm tmp0
name=Barbara Miller
city=Brooklyn
@VictorPulzz
Copy link

@mattkenefick Hey thanks for you example can you help me, I need merge to env files with update values. For example:
.env1
A=1
B=3

.env2
A=2
B=3
D=5

.env.result
A=2
B=3
D=5

help please)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment