Monday, October 24, 2022

[SOLVED] Quantitavely replace digit (as counter) with string in sed

Issue

Let's say i have the following file:

balloons:
 - 2
 - 3

Each number above should represents how many times i want to print the string. So for example I would like to process this to output as following:

balloons:
- red
- red
- blue
- blue
- blue

I only have red and blue balloons. The digits will vary from one file to another, so my search string would be a simple regex search sed -e "/[[:digit:]]\+/ perform_my_action"


Solution

Try:

awk 'BEGIN{idx[2]="red"; idx[3]="blue"}
/^-[ \t]+[0-9]+/{for(i=1;i<=$2;i++) print idx[$2]; next}
1
' file


Answered By - dawg
Answer Checked By - Marie Seifert (WPSolving Admin)