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.
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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.