Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding spaces after each character in a string

I have a string variable in my script, made up of the 9 permission characters from ls -l

eg:

rwxr-xr--

I want to manipulate it so that it displays like this:

r w x     r - x     r - -

IE every three characters is tab separated and all others are separated by a space. The closest I've come is using a printf

printf "%c %c %c\t%c %c %c\t%c %c %c\t/\n" "$output"{1..9}

This only prints the first character but formatted correctly

I'm sure there's a way to do it using "sed" that I can't think of

Any advice?

like image 729
Moe45673 Avatar asked Jul 04 '26 01:07

Moe45673


2 Answers

Using the Posix-specified utilities fold and paste, split the string into individual characters, and then interleave a series of delimiters:

fold -w1 <<<"$str" | paste -sd'  \t'
like image 50
rici Avatar answered Jul 05 '26 16:07

rici


$ sed -r 's/(.)(.)(.)/\1 \2 \3\t/g' <<< "$output"
r w x   r - x   r - -   

Sadly, this leaves a trailing tab in the output. If you don't want that, use:

$ sed -r 's/(.)(.)(.)/\1 \2 \3\t/g; s/\t$//' <<< "$str"
r w x   r - x   r - -
like image 40
John Kugelman Avatar answered Jul 05 '26 15:07

John Kugelman



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!