Reputation: 642
How can I number the occurrences of the matched pattern using sed. For eg: I have a file with data in the format :
line1
line2
line3
********
line4
line5
********
line6
line7
line8
line9
*******
line10
And I need the output in the format below:
line1
line2
line3
1*******
line4
line5
2*******
line6
line7
line8
line9
3******
line10
So, the basic requirement is replacing the first occurrance of /^\*/ with 1, second occurrance with 2, third with 3 and so on.
Upvotes: 0
Views: 114
Reputation: 58488
This might work for you (GNU sed):
sed -r '/^\*/!b;x;:a;s/9(_*)$/_\1/;ta;s/^(_*)$/0\1/;s/$/:9876543210/;s/(.)(_*):.*(.)\1.*/\3\2/;s/_/0/g;x;G;s/(.*)\n(.*)/\2\1/' file
As a solution it is little more than a joke, however where there's a will there's a way
.
Upvotes: 2
Reputation: 27577
Use awk instead:
awk '{if ($0 ~ /[*]+/) printf "%d%s\n", ++a, substr($0, 2); else print $0;}' file
Upvotes: 0
Reputation: 242028
sed
cannot do any arithmetics. Use a different tool, e.g. Perl:
perl -pe 'print ++$i if /^\*+$/' file
Upvotes: 2
Reputation: 785651
Use the right tool for the right job. This is tailor made job for awk:
awk '$1 ~ /\*\*\*\*/{print ++a $0; next} {print}' file
line1
line2
line3
1********
line4
line5
2********
line6
line7
line8
line9
3*******
line10
Or else pure BASH solution:
while read l; do
[[ $l == *'****'* ]] && l=$((++x))"$l"
echo "$l"
done < file
Upvotes: 2