0

I am trying to turn a file like this to something at the bottom. I am unsure of how to use awk or paste to go about this.

0.0000000000  0.0000000000  0.0000000000 
0.7804643317  0.5703578412   0.0000000000 
-0.7804643317  0.5703578412   0.0000000000 

I would be dealing with a changing number of rows for the file I'm trying to transform.

0.0000000000 0  0.0000000000 0  0.0000000000 0
0.7804643317 0  0.5703578412 0  0.0000000000 0
-0.7804643317 0  0.5703578412 0  0.0000000000 0
1
  • I think you meant "the number of rows would stay at three, but the number of columns would change"?
    – Ray
    Sep 16 at 3:53
4

I'd use sed:

sed -i -E 's/([^ ]+)/\1 0/g' file

or if the file is tab-delimited:

sed -i -E 's/([^\t]+)/\1\t0/g' file
  • -i edit file inplace.
  • s/pattern/replacement/ means substitute pattern with a replacement string.

OR awk

awk -i inplace '{for (f=1;f<=NF; f++){$f=$f" 0"}}1' file

or

awk -i inplace '{for (f=1;f<=NF; f++){$f=$f"\t0"}}1' file

However, most implementations do not support -i inplace. Then, you need to write your output to a temp file and overwrite the original file with that:

awk '{for (f=1;f<=NF; f++){$f=$f" 0"}}1' file > file.tmp && mv file.tmp file
0
2

A Perl approach:

$ perl -ane 'print "$_ 0 " for @F; print "\n"' file
0.0000000000 0 0.0000000000 0 0.0000000000 0 
0.7804643317 0 0.5703578412 0 0.0000000000 0 
-0.7804643317 0 0.5703578412 0 0.0000000000 0 

Or, to edit the original file:

perl -i -ane 'print "$_ 0 " for @F; print "\n"' file
0

Added help from: https://unix.stackexchange.com/questions/11801/replace-all-white-spaces-with-commas-in-a-text-file

$ cat text.file | sed 's/[[:blank:]]\+/\ 0\ /g'

 0.0000000000 0 0.0000000000 0 0.0000000000 0
 0.7804643317 0 0.5703578412 0 0.0000000000 0
 -0.7804643317 0 0.5703578412 0 0.0000000000 0

or prettify with column:

$ cat text.file | sed 's/[[:blank:]]\+/\ 0\ /g' | column -t -e

 0.0000000000   0  0.0000000000  0  0.0000000000  0 
 0.7804643317   0  0.5703578412  0  0.0000000000  0
 -0.7804643317  0  0.5703578412  0  0.0000000000  0

Beware this accounts for empty spaces at the end of the string. Might want to filter with a prior sed.

 $ cat text.file | sed 's/[[:blank:]]\+$//g' | sed 's/[[:blank:]]\+/\ 0\ /g' | column -t -e

 0.0000000000   0  0.0000000000  0  0.0000000000 
 0.7804643317   0  0.5703578412  0  0.0000000000
 -0.7804643317  0  0.5703578412  0  0.0000000000
2
  • Note that you don't need cat there. You can give the file to sed as an argument. You also don't need to escape the spaces.
    – terdon
    Sep 16 at 17:20
  • You probably want to use something like [[: blank:]]\+\|$ (although there are spaces at the end of the example, newline is probably more common).
    – bac0n
    Sep 16 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.