Would like to replace my third field (empty) for each five lines by
foo. This command is not correct. Can you help me fix it ?
!perl -pe 's(&&)($n++ = 5 ? (&foo&)eg' text.txt
I'm afraid that your syntax and semantics have enough wrong that it
would take a while to explain.
I think that approach is barking up the wrong tree anyway. It looks
more like array element manipulation than string processing. I think
it's easier to use split(), either explicitly or implicitly, to split
the input into an array, and then just manipulate $field[2].
You didn't explicitly specify what to do
- if the third field is not empty.
I gather that you would want it to be left alone.
- if there is no third field.
I assume that no third field is to be added.
and the test data didn't include it such test cases.
I also include a test case to make sure that the right number of empty
fields (other than the third) are preserved.
perl '-F&' -wape 'use strict;
if (@F > 2 && $F[2] eq "") {
$F[2] = "foo"; $_ = join("&", @F);
}' 093.txt
applied to
xxxx&(ght)(hgf)&&(yyt)
xx9x&(gg)(ff)&&(yyt)
oixxx&(hfd)(jj)&&(yyt)
xxxx&(jj)(kk)&&(yyt)
xjhxxx&(jj)(j)&&(yyt)
xjhxxx&(jj)(j)&NO FOO HERE&(yyt)
only_one_field
two&fields
&null&&fields&5 more&&&&&
produces
xxxx&(ght)(hgf)&foo&(yyt)
xx9x&(gg)(ff)&foo&(yyt)
oixxx&(hfd)(jj)&foo&(yyt)
xxxx&(jj)(kk)&foo&(yyt)
xjhxxx&(jj)(j)&foo&(yyt)
xjhxxx&(jj)(j)&NO FOO HERE&(yyt)
only_one_field
two&fields
&null&foo&fields&5 more&&&&&
(I don't know a variable to use instead of the repeated "&".)