francesco
francesco

Reputation: 7539

insert columns to file with bash or alike

Suppose I have a file like

1 3 44 5
2 23 1 44

and I would like to add two columns of 0s after the first two, to get

1 3 0 0 44 5
2 23 0 0 1 44

I could use something like

cat file|(
for ((i=0;i<nlines;i++))
do
   read l
   echo $(echo $l|cut -d" " -f -2) 0 0 $(echo $l|cut -d " " -f 3-)
done
) >output

where nlines is the known number of lines. But this happens to be extremely slow.

What is the way to do the job in a fast way? Bash, awk or other linux command-line tools are ok.

Upvotes: 2

Views: 779

Answers (5)

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed -i 's/\S\+/& 0 0/2' file

Replace the 2nd column by itself and append 0 0.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133538

With your shown samples, please try following awk code.

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

Explanation: Simply adding space and 2 zeros(separated by spaces) followed by space into 2nd field itself and printing the current line.

Upvotes: 1

dawg
dawg

Reputation: 103874

You can use sed too:

sed -E 's/^([^[:space:]]*[[:space:]]*[^[:space:]]*)(.*)$/\1 0 0\2/' file

Or ruby:

ruby -lane 'puts ($F[0..1]+["0"]*2+$F[2..]).join(" ")' file

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246847

Perl is good for fast text manipulations. Here, you could do

perl -i.bak -lane 'splice @F, 2, 0, (0, 0); print join " ", @F' file

Upvotes: 1

anubhava
anubhava

Reputation: 785246

Using awk you can do:

awk '{$3 = "0 0 " $3} 1' file

1 3 0 0 44 5
2 23 0 0 1 44

Or this sed would also work:

sed -i.bak -E 's/^(([^ ]+ +){2})/\10 0 /' file

cat file

1 3 0 0 44 5
2 23 0 0 1 44

Upvotes: 2

Related Questions