Last Updated: February 25, 2016
·
1.275K
· mannytoledo

Use Full Path to Generate File Names Using Awk

I had to collect the same config file from multiple projects and put them in one place so that I could push the configs out with some modifications to each one on deployment. I decided to use the directory name to generate the name of the config file so that I would easily be able to identify them.

Given the following paths to conf files:

/home/user/projects/preprod/app1_build/config/app.conf
/home/user/projects/preprod/app2_build/config/app.conf
/home/user/projects/preprod/app3_build/config/app.conf
/home/user/projects/preprod/blog_build/config/app.conf
/home/user/projects/production/app1_build/config/app.conf
/home/user/projects/production/app2_build/config/app.conf
/home/user/projects/production/app3_build/config/app.conf
/home/user/projects/production/blog_build/config/app.conf

I used a bash for loop from the command line to take each full path and pass it to awk. Iniside of awk I split on / and had it run a system command that copied each file to /home/user/renamed_project_configs then used the column number to pull the directory names used to construct the filename.

for i in `find /home/user/projects -name app.conf`; do echo $i|awk '{split($0,a,"/"); command = "cp "$0" /home/user/renamed_project_configs/" a[4]"."a["5"]"."a[7]; system(command)}'; done

The result was that line /home/user/projects/preprod/app2_build/config/app.conf would create file /home/user/renamed_project_configs/preprod.app2_build.app.conf pulling from column 4 (preprod), column 5 (app2_build), and column 7 (app.conf).

References:
Assigning System Commands in Awk,
Split String to Array Using Awk