Appending contents to a file if doesn't exist

2019-07-13 16:47发布

We have a file named parameters.txt which contains in comma separated value:

db.hostname,db.username,db.password,db.url,db.status,codesettingsA, codesettimgsB

Also, we have a main file called properties.txt which contains in Line format

db.hostname=hostname
db.username=username
db.password=password

I need to pass the comma separated values in parameters.txt and check whether if it is exist in properties.txt. If it is not exist it should print bottom of the properties.txt

For Example, in the properties.txt: db.url, db.status, codesettingsA and codesettimgsB is not there. However, I’m passing from the parameters.txt. It should be appended and the result should be like this in properties.txt:

db.url
db.status
codesettingsA
codesettimgsB

Note: Already values are declared for db.hostname=hostname, db.username=username and db.password=password in properties file. I'm passing db,hostname,db.username,db.password from parameter file. So, this should ignore the values even after the comma and shouldn't print db,hostname,db.username,db.password

Is there any ways to print them at the bottom page of properties.txt? Can you provide sample code?

标签: bash shell unix
3条回答
爷、活的狠高调
2楼-- · 2019-07-13 17:36

You can use this awk:

awk 'FNR==NR{for (i=1; i<=NF; i++) a[$i]; next} $1 in a{delete a[$1]} 1;
   END{for (i in a) print i "="}' FS=' *, *' params.txt FS=' *= *' props.txt

Output:

db.hostname=hostname
db.username=username
db.password=password
codesettimgsB=
db.url=
codesettingsA=
db.status=
查看更多
Emotional °昔
3楼-- · 2019-07-13 17:42
cat properties.txt <(grep -vf properties.txt <(tr ',' '\n' <parameters.txt))

tr .. converts csv formatted records to newline separated, grep .. find the lines not in parameter.txt and cat .. appends them

查看更多
手持菜刀,她持情操
4楼-- · 2019-07-13 17:51

Try this :

IFS=',' read -ra params < parameters.txt
for param in "${params[@]}"; do
  grep "$param" properties.txt || echo "$param" >> properties.txt
done

Parameters are parsed and stored into a params array.

For each parameter, the loop checks if it's present in properties.txt and, if not, append it at the bottom of the file.

查看更多
登录 后发表回答