Search

bash split string every n characters

bash split string every n characters

Today I needed to split a string in bash every 5 characters.

Here is how I did it:

a="AdmitAfritAmbitAuditAwaitBefitBinitBruitCubitDavitDebitDemitDigitDixitDroitFixitFruitHabitKraitLegitLicitLimitMeritOrbitPetitPewitPipitPlaitPositQubitQuoitRecitRefitRelitRemitResitSpaitSplitSpritTacitTraitUnfitUnlitUnwitUplitVisitVomitZizit"
count=5 # change 5 to however many characters you wish to break on
b="$a"
while [ "$b" != "" ]; do
echo "${b:0:$count}"
b="${b:$count}"
done

I hope this snippet helps somebody. If it does, please feel free to leave a comment – I enjoy interacting with visitors to my corner of the internet :)

Related posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.