-2

I've found this thread:

How to insert a new line character after a fixed number of characters in a file

but the answers there unfortunately don't help me.

I have this huge string $temp that I want to have cut off after a specific amount of characters (e.g. 20) to match it with the line above. After that number of characters there should be added a \n and in the end the formatted string should be inserted into a variable. There should be no cutting if the length of the string is < the number.

Right now I'm sticking to

sed -e "s/.\{20\}/&\n/g" <<< $temp

but it doesn't work. Instead of adding \n it's adding spaces.

Community
  • 1
  • 1
Damian
  • 19
  • 1
  • 5
  • 1
    Why are you not using the accepted answer in the link you included? It works when what you're "sticking to" doesn't! Also you need to clarify what it is you want because as written it's not clear. You should also provide a sample of what `$temp` holds and an example of your expected output. – user3439894 Aug 07 '15 at 10:45

2 Answers2

0

The easiest is probably to use the fold utility, as suggested in the thread you referenced. For instance:

printf "%s\n" "$temp" | fold -cw 20

When you say:

to match it with the line above

...Perhaps it would be helpful to try the uniq program to weed out (or count) duplicates:

printf "%s\n" "$temp" | fold -cw 20 | uniq

And of course, if you want the output in a new variable, wrap it in $() like so:

new="$(printf "%s\n" "$temp" | fold -cw 20 | uniq)"
traal
  • 461
  • 3
  • 7
0
NewTemp="$( printf "%s" "${temp}" | sed -e 's/.\{20\}/&\
/g' )"
  • Your sed is fine but it is always a bit tricky when source and destination are the same if application is not specifically taking this into accound (like option -i of GNU sed).
  • use simple quote if possible (not substituion needed)
  • i prefer to use a real new line (when not onliner) instead of \n to availbel on each sed version (posix does not allow \n in replacement pattern)
  • just be sure of the meaning of existing new line in temp variable
    • sed work line per line by default (so each line is take one by one)
    • if using multiline (option or loading buffer), new line IS also a character take by .
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43