LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sed - express strings of dots (https://www.linuxquestions.org/questions/programming-9/sed-express-strings-of-dots-4175455427/)

danielbmartin 03-24-2013 09:08 PM

sed - express strings of dots
 
These are contrived examples ...
Code:

st="abcdefghijklmnopqrstuvwxyz"
sed 's/\(.......\)/\1\n/g' <<< $st
sed 's/\(..........\)/\1\n/g' <<< $st
sed 's/\(.............\)/\1\n/g' <<< $st

All three seds produce the expected results.

Question: how may the sed be written to parameterize the number of dots?
Is there a shorthand to express a string of 13 dots as '.'{13} or somesuch?
Is there a shorthand to express a string of n dots as '.'{$n} or somesuch?

Daniel B. Martin

rknichols 03-24-2013 09:22 PM

Sure. You can either introduce the "[" and "]" characters with "\" to tell sed that they are special
Code:

sed -e 's/\(.\{13\}\)/\1\n/'
or tell sed to use extended regular expressions, which will make both the parentheses and curly brackets special unless escaped by a backslash.
Code:

sed -r -e 's/(.{13})/\1\n/'
All of the features of extended regular expressions are available in standard expressions. It's just that the need to use backslashes to introduce some characters (i.e., mark them as special) in a standard expression reverses to a need to escape them (mark them as literal) in an extended expression.

danielbmartin 03-24-2013 09:45 PM

Quote:

Originally Posted by rknichols (Post 4918029)
Sure. You can either introduce the "[" and "]" characters with "\" to tell sed that they are special
Code:

sed -e 's/\(.\{13\}\)/\1\n/'
or tell sed to use extended regular expressions, which will make both the parentheses and curly brackets special unless escaped by a backslash.
Code:

sed -r -e 's/(.{13})/\1\n/'

Thank you, rknichols, this is precisely what is needed.

I generalized your sample code this way:
Code:

echo; echo "Method #1 of LQ Member rknichols"
nc=5
st="abcdefghijklmnopqrstuvwxyz"
sed -e 's/\(.\{'$nc'\}\)/\1\n/g' <<< $st

echo; echo "Method #2 of LQ Member rknichols"
nc=5
st="abcdefghijklmnopqrstuvwxyz"
sed -r -e 's/(.{'$nc'})/\1\n/g' <<< $st

... and it produced the desired results ...
Code:

Method #1 of LQ Member rknichols
abcde
fghij
klmno
pqrst
uvwxy
z

Method #2 of LQ Member rknichols
abcde
fghij
klmno
pqrst
uvwxy
z

SOLVED!

Daniel B. Martin


All times are GMT -5. The time now is 10:22 AM.