Home How to use awk to edit lines in a file
Reply: 1

How to use awk to edit lines in a file

CarComp
1#
CarComp Published in 2017-12-06 13:36:30Z

I have a file that has a bunch of unique entries in it, each one on its own line. I'm trying to take some system variables I've created and insert them into the file on the respective line. I keep getting it inserted on the next line, or a random carriage return.

Here is an example of the file:

[default]
access_key =
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com

Here is the script / commands I've figured out so far:

accesskey="ACCESSKEYWOULDENDUPHERE"
awk -i inplace -v x="$accesskey" '{print} /access_key =/ {print x}' /root/.s3cfg

This is what happens

[default]
access_key =
ACCESSKEYWOULDENDUPHERE
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com

As you can see, I end up inserting on a new line.

My goal is for it to look like this:

[default]
access_key = ACCESSKEYWOULDENDUPHERE
bucket_location = US
cloudfront_host = cloudfront.amazonaws.com

I am trying to figure out how to use printf but its just not working out so far.

Inian
2#
Inian Reply to 2017-12-06 14:04:01Z

To set the access_key value all you need to do is set the delimiter as = and match the field in $1 to contain access_key (remember the trailing whitespace) and update the $2 value accordingly. The reason is for absolute strings (not changing like access_key), it would be more easy to do a direct comparison than do a regex match of it.

awk -v x="$accesskey" -vFS='=' -vOFS='=' '$1 == "access_key "{$2=" "x}1' file

Add the -i inplace flag once you find it working as you wanted it.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296657 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO