Hendrik
Hendrik

Reputation: 75

SED find and Replace Text with SED or AWK?

I'm trying to do the first one all morning here. But I can't get ahead, can anyone help me?

DE
  RDT;136618;0.0%;100.0%
  RD;7379;97.8%;2.2%
IT
  RDT;69424;97.0%;3.0%
  RD;585;98.7%;0.0%
FR
  RDT;22870;96.5%;3.5%
  RD;440;98.8%;0.0%
UK
  RDT;33167;97.7%;2.3%
  RD;438;97.3%;0.1%
ES
  RDT;99860;96.9%;3.1%
  RD;391;97.9%;0.1%

RDTDE;136618;0.0%;100.0%
RDDE;7379;97.8%;2.2%
RDTIT;69424;97.0%;3.0%
RDIT;585;98.7%;0.0%
RDTFR;22870;96.5%;3.5%
RDFR;440;98.8%;0.0%
RDTUK;33167;97.7%;2.3%
RDUK;438;97.3%;0.1%
RDTUK;99860;96.9%;3.1%
RDUK;391;97.9%;0.1%

I want to merge the code, Entering in one step or in several steps. In several would be better, then I can understand what has been done here.

Upvotes: 0

Views: 53

Answers (5)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed -nE '/^\S/h;G;s/^\s+([^;]*)(.*)\n(.*)/\1\3\2/p' file

Save county ids to the hold space. Append the hold space to other lines and using pattern matching achieve the required result.

Upvotes: 1

Tyl
Tyl

Reputation: 5252

Another awk, more compatible:

awk '/^[A-Z]*$/{cc=$0;next}sub(/^ +/,"")+sub(";",cc ";")' file
RDTDE;136618;0.0%;100.0%
RDDE;7379;97.8%;2.2%
RDTIT;69424;97.0%;3.0%
RDIT;585;98.7%;0.0%
RDTFR;22870;96.5%;3.5%
RDFR;440;98.8%;0.0%
RDTUK;33167;97.7%;2.3%
RDUK;438;97.3%;0.1%
RDTES;99860;96.9%;3.1%
RDES;391;97.9%;0.1%

If the leading spaces do not need to be removed, you can remove sub(/^ +/,"")+ this part.

If you have GNU awk, then can do it like this:

awk '/^[A-Z]{2}$/{cc=$0;next}{print gensub(/^\s*([^\s;]+)/, "\\1" cc, 1)}' file

Upvotes: 0

karakfa
karakfa

Reputation: 67467

another awk

$ awk -F';' 'NF==1{s=$1;next} {sub(";",s ";"); sub(" +","")}1' file

RDTDE;136618;0.0%;100.0%
RDDE;7379;97.8%;2.2%
RDTIT;69424;97.0%;3.0%
RDIT;585;98.7%;0.0%
RDTFR;22870;96.5%;3.5%
RDFR;440;98.8%;0.0%
RDTUK;33167;97.7%;2.3%
RDUK;438;97.3%;0.1%
RDTES;99860;96.9%;3.1%
RDES;391;97.9%;0.1%

Upvotes: 0

jas
jas

Reputation: 10865

 $ awk 'BEGIN {OFS=FS=";"} NF == 1 {country = $1; next} {$1 = $1 country}1' file
  RDTDE;136618;0.0%;100.0%
  RDDE;7379;97.8%;2.2%
  RDTIT;69424;97.0%;3.0%
  RDIT;585;98.7%;0.0%
  RDTFR;22870;96.5%;3.5%
  RDFR;440;98.8%;0.0%
  RDTUK;33167;97.7%;2.3%
  RDUK;438;97.3%;0.1%
  RDTES;99860;96.9%;3.1%
  RDES;391;97.9%;0.1%

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133428

Could you please try following(tested on provided samples only).

awk 'BEGIN{OFS=FS=";"}!/^ /{val=$0;next} val{sub(/^ +/,"");$1=$1 val} val' Input_file

Upvotes: 0

Related Questions