![]() ![]() If the M is not used, the ^foo will match only on the first line (at the start of the pattern space).Īn alternative to M is: $ printf 'foo\0foo\0foo\0' | sed -z 'H 1h $!d x l s/\(^\|\x0\)foo/ baz /2' The l allow us to see what is inside the pattern space, and the M flag is required so that the ^ is matching more that the first line. and then try the ^foo substitution: $ printf 'foo\0foo\0foo\0\n' | sed -z 'H 1h $!d x l s/^foo/ baz /M2' ![]() We can get the whole input file inside sed pattern space by using H 1h $!d x. No, it doesn't work if the input has NULs ( \0), those would be treated as line delimiter (or, in awk parlance, as record separators). In fact, for the substitution to work correctly, the whole input needs to be in the pattern space. Remember: the use of -z is experimental and might lead to odd problems. It makes no sense to think of "start of the line" with ^ when using '-z'. The problem is: where does a line start? at a newline or at a \0, or both?, or none? Oops, no there are not enough foo at the start of the line either. In echo $'foo\nfoo\nfoo' | sed -z 's/^foo/baz/2' there are not enough foo in each line to make it possible to change the second, but in this next example: should it be? $ printf 'foo foo foo\nfoo foo foo\n' | sed -z 's/^foo/baz/2' ![]() The sed command changed the second (2) instance of foo with bar but for each line that it got applied to (all of them). In $ printf '%s\n' 'foo foo foo' 'foo foo foo' 'foo foo foo' | sed 's/foo/bar/2' First, what is the 2 (or any other number in s///2) actual meaning? It simply means that the second regex match on the line where it is applied will be changed. Is not that simple as the selected answer seems to make it. ![]()
0 Comments
Leave a Reply. |