Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell - replace string with incrementing value

Tags:

shell

awk

I have this String:

"a | a | a | a | a | a | a | a"

and I want to replace every " | " with an incrementing value like so:

"a0a1a2a3a4a5a6a"

I know I can use gsub to replace strings:

> echo "a | a | a | a | a | a | a | a" | awk '{gsub(/\ \|\ /, ++i)}1'
a1a1a1a1a1a1a1a

But it seems gsub only increments after each newline, so my solution for now would be first putting a newline after each " | ", then using gsub and deleting the newlines again:

> echo "a | a | a | a | a | a | a | a" | awk '{gsub(/\ \|\ /, " | \n")}1' | awk '{gsub(/\ \|\ /, ++i)}1' | tr -d '\n'
a1a2a3a4a5a6a7a

Which is honestly just disgusting...

Is there a better way to do this?

like image 606
encomiastical Avatar asked Dec 19 '22 09:12

encomiastical


1 Answers

If perl is okay:

$ echo 'a | a | a | a | a | a | a | a' | perl -pe 's/ *\| */$i++/ge'
a0a1a2a3a4a5a6a
  • *\| * match | surrounded by zero or more spaces
  • e modifier allows to use Perl code in replacement section
  • $i++ use value of $i and increment (default value 0)
like image 57
Sundeep Avatar answered Dec 21 '22 23:12

Sundeep