Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How different numbers are added at the beginning of each line?

I have got this file :

...
chapter 10.
1. text
2. text
text
3. text
chapter 11.
1. text
2. text
3. text
4. text
chapter 12.
1. text
text
text
2. text
...

And I need this

...
chapter 10.
10.1. text
10.2. text
text
10.3. text
chapter 11.
11.1. text
11.2. text
11.3. text
11.4. text
chapter 12.
12.1. text
text
text
12.2. text
...

I have to put the number that comes after the chapter at the beginning of all the following lines that begin with a number followed by a dot. There are lines that do not begin with a number, those would remain unchanged. Thank you very much, any help is welcome

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Perl to the rescue!

perl -i~ -pe '$ch = $1  if /^chapter ([0-9]+\.)/;
              print $ch if /^[0-9]+\./;
     ' -- file.txt
  • -p reads the input line by line, printing each line after processing;
  • -i~ saves all the changes to the original file, a backup file is created with the extension ~;
  • when a line starts with chapter XX., the number of the chapter including the final dot is saved in the variable $ch;
  • when the line starts with a number followed by a dot, the value from $ch is prepended.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading