pac88
pac88

Reputation: 11

Changing words in a file appending numbers

I have a file that has the following form:

xcart 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
xcart 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
xcart 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
............. 

That is, every three lines there is a line which starts with 'xcart'. The values of the numbers don't matter for this question.

I'd like to change every occurrence of 'xcart' for 'xcart1', 'xcart2', 'xcart3' and so on. Let's suppose that I have 120 occurrences of 'xcart'.

So, the final form of my file would be:

xcart1 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
xcart2 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
xcart3 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
.............
.............
xcart120 1.0 1.0 1.0
1.5 1.5 1.5 
3.1 2.0 0.0

Is there an easy way to do such a thing?

Thanks in advance.

Upvotes: 0

Views: 46

Answers (1)

Kent
Kent

Reputation: 195179

awk is happy to do this kind of job:

awk '$1=="xcart"{$1=$1"" ++i}7' file

with your example:

kent$  awk '$1=="xcart"{$1=$1"" ++i}7' f
xcart1 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
xcart2 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0
xcart3 1.0 1.0 1.0
1.5 1.5 1.5
3.1 2.0 0.0

Upvotes: 1

Related Questions