I'm trying to add an incrementing value to a file based on the value e.g. which changes anytime it finds 'E' (this can be replaced with any value) From some online research I've tried:
awk '/E/{sub("E", "E"++v)}1' output.txt > output2.txt
but that only adds an incremental value after the 'E' itself. No, this is not a school assignment, this data will next be ingested into a MySQL table with that value being the ID field. Note: the 'E' will always be present at the End of the dataset. This file (a very larger version) will be ingested into MySQL table, for a word unscrambler application.
Sample file: output.txt
aaa
aba
acaE
baa
bab
badE
caa
cab
cdeE
ddd
Sample file: desired
1aaa
1aba
1acaE
2baa
2bab
2badE
3caa
3cab
3cdeE
4ddd
答案1
You can do it thus:
awk '{print i $0}; /E$/{i++}' i=1 file
We set i=1
as the initial value, because by default it is unset. {print i $0}
prints i
and the whole line $0
. Then, just check if the line matches E
and increment i
in that case.
A very similar alternative proposed by αғsнιη is
awk '{print i+1 $0}; /E$/{i++}' file
summing 1
to i
so that we do not have to initially set i=1
.