Replace characters in a text file at a certain position
Hey guys!
i have a text file and want to write a textstring at, let's say, line 5 at position 4, and REPLACE the old text at that position with the new text- so if line 5 looked like this: ABCDEFGHIJKLMNOPQRSTUVWXYZ Text to insert: hello pos 4: ABCD>EFGHIJKLMNOPQRSTUVWXYZ new line 5: ABCDhelloJKLMNOPQRSTUVWXYZ Can somebody tell me how to do this in bash, please? Thank you! |
Welcome to LQ!
Is this a homework? :) You could try with sed. |
As above, try with sed http://www.grymoire.com/Unix/Sed.html
|
You can do quite a bit (tediously) with commands such as tr, cut, join etc...
|
thanks everybody, couldn't get it to work the way i wanted to with sed, so i wrote a c program instead, using fopen etc. :)
|
I don't think there's a need to reinvent the wheel. As others said it can be done with sed
I'll post it as a little puzzle. Some basic sed knowledge is enough to solve it. Code:
sed '***********' file Code:
hello/4.s//5 Code:
sycamorex@mainframe:~/data/tmp$ cat file |
thank you, sycamorex
sed 4s/./hello/5 file so this would work to replace the 5th letter in line 4, but literally only one letter is replaced from: ABCDEFGHIJKLMNOPQRSTUVWXYZ to: ABCDhelloFGHIJKLMNOPQRSTUVWXYZ instead of: ABCDhelloJKLMNOPQRSTUVWXYZ can you point me in the right direction to replace not only one letter and then insert the string, but to delete as many characters from the input file at that position as stringlength of "hello" is? thx a ton! |
Quote:
Quote:
|
Try the following:
Code:
sed '4s/^\(.\{4\}\)\(.\{5\}\)\(.*\)/\1hello\3/' file |
All times are GMT -5. The time now is 10:10 PM. |