Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string into fixed-size pieces using sed

Tags:

bash

sed

I have a question - Im trying to split a variable stored into fixed-size by 5 characters and put a "%" after each 5. letter, with:

echo "$d" | sed 's/.\{5\}/&%/g'

Which gives me this, if the stored variable in $d is HELLOWOLRD123

HELLO%WORLD%123

How can I get to auto fill out, %% so it keeps the fixed size as 5 ?

So my output is HELLO%WOLRD%123%%%

like image 461
Neo1234 Avatar asked Dec 02 '25 00:12

Neo1234


2 Answers

If perl is okay

$ echo 'HELLOWOLRD123' | perl -pe 's/.{1,5}/$& . "%" x (6-length($&))/ge'
HELLO%WOLRD%123%%%
  • .{1,5} greedy match 1 to 5 characters
  • e this modifier allows us to use Perl code in replacement section
  • $& the matched string
  • . string concatenation
  • "%" x (6-length($&)) here x is string repetition operator
like image 107
Sundeep Avatar answered Dec 03 '25 14:12

Sundeep


One in awk:

$ echo HELLOWOLRD123 | 
  awk '{gsub(/.{1,5}/,"&%");while(length($0)%6)sub(/$/,"%")}1'
HELLO%WOLRD%123%%%

Explained some:

$ echo HELLOWOLRD123 | 
  awk '{
      gsub(/.{1,5}/,"&%")   # add % after every 5 chars
      while(length($0)%6)   # while length of string mod 6 is not 0
          sub(/$/,"%")      # add a & to it
  }1'
HELLO%WOLRD%123%%%
like image 30
James Brown Avatar answered Dec 03 '25 13:12

James Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!