Annelies
Annelies

Reputation: 47

How to replace values in a column with zeros in .txt file using bash

I have a tab delimited txt file containing 3 columns, like this:

I simply want to replace all values in the middle column with zero's, so it looks like this:

I got only as far as that I might need to use sed, but I have know idea how to specify the second column. This is what I found so far:

sed -i 's/column2/0/g' Con_Dec_0.txt

Could anybody help?

Upvotes: 1

Views: 1318

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133700

EDIT: Thanks to @socowi for letting me know on TAB delimited files so adding solution as per that now.

For tab delimited:

awk -v FS='[[:space:]]+' 'BEGIN{OFS="\t"} {$2="0";$1=$1} 1' Input_file

To save output into Input_file try following:

awk -v FS='[[:space:]]+' '{$2="0"} 1' Input_file | column -t > temp && mv temp Input_file


Since you have not posted samples in text formats so not sure what is the delimiter of your Input_file, could you please try following.

awk '{$2="0"} 1' Input_file

To save output into Input_file itself use following if Happy with above.

awk '{$2="0"} 1' Input_file > temp && mv temp Input_file

Upvotes: 3

stephanmg
stephanmg

Reputation: 766

How about this?

awk -F '[[:space:]]+' '{ print $1 "\t" 0 "\t" $2 } ' foo.txt 

Or even shorter like this:

awk -F '[[:space:]]+' '{ $2=0 } 1' foo.txt 

This should work regardless of a tab or whitespace separated CSV file.

From the manual (any run of spaces and/or tabs and/or newlines is treated as a field separator), so you might drop the -F separator. This will result in the answer posted below, i.e:

  awk '{ $2=0 } 1' foo.txt 

Edit: Need to change * (single or more matches) to + (one or more matches).

Upvotes: 1

Socowi
Socowi

Reputation: 27320

Using sed is possible.

sed 's/\t[^\t]*/\t0/' yourFile

[^\t]* matches as many non-tab characters as possible, that is, the 2nd field because we required that there is a \t in front of it. Note the missing /g at the end – we only replace the first occurrence, that is, the 2nd column.

However, for the general case of replacing column n with a value it is easier to use an awk script.

awk -F '\t' '{OFS="\t"; $2=0; print}' yourFile

-F sets the field separator for the input.
OFS sets the field separator for the output.
The part inside {...} is executed for each line.
$2=... changes the 2nd column.
print prints all fields using the output separator.

Upvotes: 1

Related Questions