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

BASH/SED: Match a line, then repeat that line n times immediately after match

Let’s say I have a file called template.inp containing the following:

filename
clustername
>>>>
repeatline 0. 0. 0. z. z. z.
>>>>
do_something.sh
>>>>

And I want to match on repeatline and then copy that whole line $repeatnum times, such that template.inp looks like for repeatnum=2:

filename
clustername
>>>>
repeatline 0. 0. 0. z. z. z.
repeatline 0. 0. 0. z. z. z.
repeatline 0. 0. 0. z. z. z.
>>>>
do_something.sh
>>>>

Not sure how to do this elegantly.

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 :

I don’t think it’s easy to do repeat a line a variable number of times in sed. But you can do it with a simple shell loop.

while read -r line; do
    echo "$line"
    if [[ "$line" == repeatline* ]]
        for ((i=0; i<repeatnum; i++)) do
            echo "$line"
        done ;;
    fi
done < template.inp > template.outp
mv template.outp template.inp
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