Pregunta

I have a text file like this:

AAAAAA this is some content.
This is AAAAAA some more content AAAAAA. AAAAAA
This is yet AAAAAA some more [AAAAAA] content.

I need to replace all occurrence of AAAAAA with an incremented number, e.g., the output would look like this:

1 this is some content.
This is 2 some more content 3. 4
This is yet 5 some more [6] content.

How can I replace all of the matches with an incrementing number?

¿Fue útil?

Solución

Here is one way of doing it:

$ awk '{for(x=1;x<=NF;x++)if($x~/AAAAAA/){sub(/AAAAAA/,++i)}}1' file
1 this is some content.
This is 2 some more content 3. 4
This is yet 5 some more [6] content.

Otros consejos

A perl solution:

perl -pe 'BEGIN{$A=1;} s/AAAAAA/$A++/ge' test.dat

This might work for you (GNU sed):

sed -r ':a;/AAAAAA/{x;:b;s/9(_*)$/_\1/;tb;s/^(_*)$/0\1/;s/$/:0123456789/;s/([^_])(_*):.*\1(.).*/\3\2/;s/_/0/g;x;G;s/AAAAAA(.*)\n(.*)/\2\1/;ta}' file

This is a toy example, perl or awk would be a better fit for a solution.

The solution only acts on lines which contain the required string (AAAAAA).

The hold buffer is used as a place to keep the incremented integer.

In overview: when a required string is encountered, the integer in the hold space is incremented, appended to the current line, swapped for the required string and the process is then repeated until all occurences of the string are accounted for.

Incrementing an integer simply swaps the last digit (other than trailing 9's) for the next integer in sequence i.e. 0 to 1, 1 to 2 ... 8 to 9. Where trailing 9's occur, each trailing 9 is replaced by a non-integer character e.g '_'. If the number being incremented consists entirely of trailing 9's a 0 is added to the front of the number so that it can be incremented to 1. Following the increment operation, the trailing 9's (now _'s) are replaced by '0's.

As an example say the integer 9 is to be incremented:

9 is replaced by _, a 0 is prepended (0_), the 0 is swapped for 1 (1_), the _ is replaced by 0. resulting in the number 10.

See comments directed at @jaypal for further notes.

Maybe something like this

#!/bin/bash
NR=1
cat filename  while read line
do
   line=$(echo $line | sed 's/AAAAA/$NR/')
   echo ${line}
   NR=$((NR + 1 ))
done

Perl did the job for me

perl -pi -e 's/\b'DROP'\b/$&.'_'.++$A /ge' /folder/subfolder/subsubfolder/*

Input:

DROP
drop
$drop
$DROP
$DROP="DROP"
$DROP='DROP'
$DROP=$DROP
$DROP="DROP";
$DROP='DROP';
$DROP=$DROP;
$var="DROP_ACTION"
drops
DROPS
CODROP
'DROP'
"DROP"
/DROP/

Output:

DROP_1
drop
$drop
$DROP_2
$DROP_3="DROP_4"
$DROP_5='DROP_6'
$DROP_7=$DROP_8
$DROP_9="DROP_10";
$DROP_11='DROP_12';
$DROP_13=$DROP_14;
$var="DROP_ACTION"
drops
DROPS
CODROP
'DROP_15'
"DROP_16"
/DROP_17/
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top