Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

🍿 Bash: cut & prepend

Snacks (🍿) are my collection of recipes for solving problems. Often recorded (and cleaned up) from actual discussions where I'm involved in helping others with technical problems. Not all solutions are mine but I started collecting them in one place because you never know when you need one.

I have a Python script that prints out 30 lines after being run. How do I remove the first 32 characters at the beginning and add `./script.sh` before them?

My first suggestion was to change it in Python (with f'./script.sh {message[32:]}') but turned out they couldn't change the Python code and needed a shell solution.

My first solution uses cut and sed:

cat example | cut -c 33- | sed 's/^/.\/script.sh /g'

Then Tero showed how to do it in sed only:

cat example | sed 's,^.\{32\},./script.sh ,'

and finally we learned that the goal was to run the script (this is a classic example from my side of just answering the question without actually trying to find out what the goal is) for each of those so the final result (by Tero) ended up with:

cut -c33- example | xargs -I _ ./script.sh _