I'm not an expert in bash coding and I'm trying to do one interative-like code to help me in my work.
I have a file that contains some numbers (coordinates), and I'm trying to make a code to read some specific numbers from the file and then store them in an array. Modify that array using some arithmetic operation and then replace the numbers in the original file with the modified array. So far I've done everything except replacing the numbers in the file, I tried using sed but it does not change the file. The original numbers are stored in an array called "readfile" and the new numbers are stored in an array called "d".
I'm trying to use sed in this way: sed -i 's/${readfile[$j]}/${d[$k]}/' file.txt
And I loop j and k to cover all the numbers in the arrays. Everything seems to work but the file is not being modified. After some digging, I'm noticing that sed is not reading the value of the array, but I do not know how to fix that.
Your help is really appreciated.
CodePudding user response:
When a file isn't modified by sed -i
, it means sed
didn't find any matches to modify. Your pattern is wrong somehow.
After using "
instead of '
so that the variables can actually be evaluated inside the string, look at the contents of the readfile
array and check whether it actually matches the text. If it seems to match, look for special characters in the pattern, characters that would mean something specific to sed
(the most common mistake is /
, which will interfere with the search command).
The fix for special characters is either to (1) escape them, e.g. \/
instead of just /
, or (2) (and especially for /
) to use another delimiter for the search/replace command (instead of s/foo/bar/
you can use s|foo|bar|
or s,foo,bar,
etc - pretty much any delimiter works, so you can pick one that you know isn't in the pattern string).
If you post data samples and more of your script, we can look at where you went wrong.