Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace space in a specific column with a character

Tags:

sed

awk

I have data in format

A  ((!(A1+A2)))
B  (A1+A2)
C  (A1 A2)
D  (!(A1 A2) B1)
E  (!A1+!A2)
F  ((A1+A2) A3 A4)
G  ((A1 A2)+(A3 A4))

I want output as

A  ((!(A1+A2)))
B  (A1+A2)
C  (A1&A2)
D  (!(A1&A2)&B1
E  (!A1+!A2)
F  ((A1+A2)&A3&A4)
G  ((A1&A2)+(A3&A4))

So whenever there is space in column2 I want it to get replaced with & I tried

sed 's/ /&/2' file

But there is no change I also tried

awk -F' ' '{if($2==" ")$2="&";}1' file

This also has no change getting back input file only.

like image 910
Shreya Avatar asked Mar 14 '26 23:03

Shreya


2 Answers

You may use this awk with 2 spaces as input/output field separator:

awk 'BEGIN {FS=OFS="  "} {gsub(/ +/, "\\&", $2)} 1' file

A  ((!(A1+A2)))
B  (A1+A2)
C  (A1&A2)
D  (!(A1&A2)&B1)
E  (!A1+!A2)
F  ((A1+A2)&A3&A4)
G  ((A1&A2)+(A3&A4))
like image 126
anubhava Avatar answered Mar 17 '26 04:03

anubhava


You can harness sed for this task following way:

sed 's/\([^ ]\) \([^ ]\)/\1\&\2/g'

gives for input

A  ((!(A1+A2)))
B  (A1+A2)
C  (A1 A2)
D  (!(A1 A2) B1)
E  (!A1+!A2)
F  ((A1+A2) A3 A4)
G  ((A1 A2)+(A3 A4))

output

A  ((!(A1+A2)))
B  (A1+A2)
C  (A1&A2)
D  (!(A1&A2)&B1)
E  (!A1+!A2)
F  ((A1+A2)&A3&A4)
G  ((A1&A2)+(A3&A4))

Explanation: I used capturing groups here, 1st is any character but space, 2nd is also any character but space and there is space between them, such match is replaced by content of 1st group (\1) followed by & (\&) followed by content of 2nd group (\2). Note that we want multiple replacements, hence g. Disclaimer: this solution assumes there are not leading or trailing spaces in your input.

like image 22
Daweo Avatar answered Mar 17 '26 04:03

Daweo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!