Programmer
Programmer

Reputation: 439

change a particular column value using awk / sed

I have a file with 52 columns. I want to replace 11th column from 0 to 1. All the data in my file are "|" separated. I tried the below command.

awk -F \| '{$11=1; print}' input_file.txt 

I have got the 11th column replaced with above command. But the output of this file changed the separator to "space". I cannot just remove space from outfile, because few columns have valid spaces as well.

Upvotes: 0

Views: 1634

Answers (3)

ctac_
ctac_

Reputation: 2471

You can try with this sed:

sed -E 's/(([^|]*\|){10})[^|]*(.*)/\11\3/' infile

If you want only change from 0 to 1

sed -E 's/(([^|]*\|){10})0(.*)/\11\3/' infile

Upvotes: 0

Jomu
Jomu

Reputation: 349

sed -re 's/(^\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|)([^|]*)\|(.*)/\11|\3/'

Filter your file through this.

Upvotes: 0

JNevill
JNevill

Reputation: 50019

Set the OFS (output field seperator) to be the same as your FS (Field Seperator which is set with your -F flag) in the BEGIN clause of your awk script otherwise it's set to the default of " "

awk -F \| 'BEGIN{OFS=FS}{$11=1; print}' input_file.txt 

Upvotes: 3

Related Questions