Search code examples
stringbashawkcutwc

How can I split a line in 2 by words/characters?


I would like to convert:

Hello Hello Hi Hello Hello Hi Hi Hi Hi Hello

Into:

Hello Hello Hi Hello
Hello Hi Hi Hi Hi Hello

I want to split a single line in 2, by having them have the closest amount of characters as possible, without cutting off a word.

I think I can probably do it with wc -w, wc -c, cut, and/or awk, but maybe you guys can provide some better ideas!


Solution

  • This can be a job for fold, a handy util to wrap lines:

    $ s="Hello Hello Hi Hello Hello Hi Hi Hi Hi Hello"
    $ fold -w $(( ${#s} / 2 + 1)) -s <<< "$s"
    Hello Hello Hi Hello
    Hello Hi Hi Hi Hi Hello
    

    This uses fold to wrap each line to a given length. And how do we calculate the length? Just using ${#variable} and dividing by 2 (+1 to prevent getting three lines if the length is odd). We then use -s to prevent breaking words.

    From man fold:

    fold - wrap each input line to fit in specified width
    
       -s, --spaces
              break at spaces
    
       -w, --width=WIDTH
              use WIDTH columns instead of 80