How to replace an entire line in a text file by line number
The question at the link above asks how to replace a line in a text file. nakeer (second answer from bottom) has provided an answer that works well for me as a Mac user:
sed -i '' -e 's/text-on-line-to-be-changed.*/text-to-replace-the=whole-line/' file-name
However, I cannot figure out how to modify it for my particular situation. If anyone can point me in the right direction, I would be very grateful.
I have many files. Each file contains this matrix, exactly as appears below:
12.345678 0.000000 0.000000 0.000000 12.345678 0.000000 0.000000 0.000000 12.345678
I have one additional file that contains a column of numbers, like:
87.654321 18.765432 21.876543 ...
I want to take one number from each line of the column in (2). I want to use it to replace the non-zero values of one matrix in (1) (preserving the zero values). So the first matrix in the first file should look like:
87.654321 0.000000 0.000000 0.000000 87.654321 0.000000 0.000000 0.000000 87.654321
The second matrix in the second file should use "18.765432" for its non-zero values.
I'm not experienced as far as bash scripting, but I so far have (where ic is my file in (1) that contains the original matrix and I copy it into a new directory where I can change that matrix to (3)):
#!/bin/bash let timesteps=20000 for ((step=0; step <= timesteps ; step++)) do mkdir $step/results cp ic $step/ic cat X >> X # <--Here I'd like to modify nakeer's expression. Any hints would be much appreciated.
Update:
- I have managed to get Ed's very clear solution up and running. There is one problem, however. The files that contain the matrices (see (1) above) also contain other data. For example (before executing Ed's code):
12.345678 0.000000 0.000000 0.000000 12.345678 0.000000 0.000000 0.000000 12.345678 0.5 abc.xyx 90 900 0.125 90 6
Ed's code successfully changes 12.345678
in the matrix to a new value. However, 0.125
in the list of numbers below the matrix is also changed to that new value. I do not want 0.125
to be changed.
Ed's code following match
seems to use the format of numbers to identify which numbers to change and it looks like 0.125
falls into the category of numbers that should be changed. If anyone has any ideas about how to exclude 0.125
from the change, I'd be grateful to know!
- How can I modify Ed's code in the case that each matrix file is in its own directory; e.g.,
0/file0, 1/file1, 2/file2
, etc?