I have this string in my data file (dat.txt) =>
00000
10101
I want to replace the 1st row, second and fourth column, I tried this:
$>sed -i "/^1/s/0/1/2" dat.txt
$>sed -i "/^1/s/0/1/4" dat.txt
But when I reload the dat.txt, it does not change anything. Is my command wrong?
For a start, unless that first line is your zeroth row, you’ll be changing the second (the one that begins with
1).And that
2and4don’t change the second/fourth column, they change the second/fourth occurrence of the search pattern.See the following transcript:
You can see that the first
sedchanged the second occurrence of0to1, and that was in the fourth column. The secondsedchanged nothing since you asked it to do it to the fourth occurrence and there aren’t four0characters there.If you want to change specific columns, you can use capturing patterns, as in the following transcript:
The parentheses capture the pattern so that
\1in the replacement text can be used to refer to that captured text. Because you’re talking about a small number of characters before the one you want to change, you can use...as a pattern. If you wanted to change (for example) the 85th column, you’d probably be better off with something like: