suren
suren

Reputation: 8796

`sed` substitude and append to the same line

I would like to substitute the dots of file by underscores and append the original line to the substituted one with colon.

So, for example I have

source.uid
source.ip
source.labels
source.name
...

I want to end up with:

source_uid: source.uid
source_ip: source.ip
source_labels: source.labels
source_name: source.name
...

Is this possible?

Upvotes: 0

Views: 79

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133770

EDIT: To cover all occurrences try following.

awk 'BEGIN{OFS=": "}{val=$0;gsub(/\./,"_");print val,$0;val=""}' Input_file

For OP's provided samples output will be as follows:

destination.workload.namespace: destination_workload_namespace

Explanation:

awk '              ##starting awk program from here.
BEGIN{             ##Starting BEGIN section from here.
  OFS=": "         ##setting OFS as colon space here.
}
{
  val=$0           ##creating variable val whose value is current line value.
  gsub(/\./,"_")   ##globally substituting dot with underscore.
  print val,$0     ##printing variable val and edited line here.
  val=""           ##Nullify Val here.
}
' Input_file



Could you please try following.

awk 'BEGIN{FS=".";OFS=": "} {print $1"_"$2,$0}' Input_file


Using sed: using sed capability of storing matched regex value into temp buffer and later use them as per need.

sed 's/\([^.]*\)\.\(.*\)/\1_\2: \1.\2/' Input_file

Upvotes: 1

Kent
Kent

Reputation: 195269

this one-liner works for the given example:

sed 's/.*/&: &/;s/\./_/' file

Test:

kent$  cat f
source.uid
source.ip
source.labels
source.name

kent$  sed 's/.*/&: &/;s/\./_/' f
source_uid: source.uid
source_ip: source.ip
source_labels: source.labels
source_name: source.name

an alternative awk one-liner that does the same:

awk '{a=$0;gsub(/[.]/,"_",a)}$0=a": "$0' file

update

If the original line has more dots ("."), the above awk one-liner should work. Also this sed line:

sed -n 'h;y/./_/;G;s/\n/: /;p' file

Test with a string:

kent$  sed -n 'h;y/./_/;G;s/\n/: /;p' <<<"a.b.c.foo.bar" 
a_b_c_foo_bar: a.b.c.foo.bar

Upvotes: 2

Related Questions