Quantcast
Channel: A Portal to a Portal
Viewing all articles
Browse latest Browse all 1850

More fun with sed

$
0
0

Problem to be solved - I was looking for a way to insert a line into a file ( it's actually related to Terraform but, for the purpose of illustration, it's just a text file ), using sed.

Here's a sample text file: -

cat simpsons.txt 

Bart
Homer
Lisa
Maggie
Marge

and I want to add a new cast member called, imaginatively, "Dave" into the list, between "Bart" and "Homer".

Here's how I can do it in sed : -

sed -i'''/^Bart/a Dave' simpsons.txt

cat simpsons.txt

Bart
Dave
Homer
Lisa
Maggie
Marge

Of course, with a basic list of text, I could've just as easily appended "Dave" to the list, and sort it: -

echo "Dave">> simpsons.txt && sort simpsons.txt --output simpsons.txt

cat simpsons.txt

Bart
Dave
Homer
Lisa
Maggie
Marge

but that doesn't work too well with a structured file.

Let's use a Terraform file for illustration: -

cat version.tf
 
terraform {
  required_providers {
    aws = {
      version = ">= 2.7.0"
      source = "hashicorp/aws"
    }
  }
}

where I want to insert backend "s3" immediately after terraform but indented with two spaces: -

sed -i'''/^terraform/a \ \ backend "s3" {}' version.tf

which results in a nicely updated file: -

cat version.tf 

terraform {
  backend "s3" {}
  required_providers {
    aws = {
      version = ">= 2.7.0"
      source = "hashicorp/aws"
    }
  }
}

I <3 sed

Viewing all articles
Browse latest Browse all 1850

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>