vj56789
vj56789

Reputation: 11

Need to prepend a string to a column and to add another column with it

I have a file with 2 lines

123|456|789
abc|123|891

I need a to output like below. Basically, I want to add the string "xyz" to col 1 and to add "xyz" as a new col 2

xyz-123|xyz|456|789
xyz-abc|xyz|123|891

This is what I used

awk 'BEGIN{FS=OFS="fs-"$1}{print value OFS $0}' /tmp/b.log

I get

xyz-123|456|789
xyz-abc|123|891

I tried

awk 'BEGIN{FS=OFS="fs-"$1}{print value OFS $0}' /tmp/b.log|awk -F" " '{$2="fs" $0;}1' OFS=" "

Upvotes: 1

Views: 267

Answers (4)

Pierre François
Pierre François

Reputation: 6083

I would use sed instead of awk as follows:

sed -e 's/^/xyz-/' -e 's/|/|xyz|/' Input_file

This prepends xyz- at beginning of each line and changes the first | into |xyz|

Upvotes: 1

Enlico
Enlico

Reputation: 28520

Another slight variation of sed:

sed 's/^/xyz-/;s/|/&xyz&/' file

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133780

Could you please try following.

awk 'BEGIN{FS=OFS="|"} {$1="xyz-"$1;$2="xyz" OFS $2} 1' Input_file

OR as per @Corentin Limier's comment try:

awk 'BEGIN{FS=OFS="|"} {$1="xyz-" $1 OFS "xyz"} 1' Input_file

Output will be as follows.

xyz-123|xyz|456|789
xyz-abc|xyz|123|891

Upvotes: 2

Kent
Kent

Reputation: 195289

In addition to the awk's updating fields ($1, $2...) approach, we can also use substitution to do the job:

 sed 's/^[^|]*/xyz-&|xyz/' file

If awk is a must:

awk '1+sub(/^[^|]*/, "xyz-&|xyz")' file

Both one-liners give expected output.

Upvotes: 2

Related Questions