0

I have this problem: I have a text file, where every line has different number of characters, like this:

aaaa
bbbbbbbbb
cc

Now I want to generate a new text file, where a line has at maximum N characters, but no content is missing. So, something like this (e.g. each line should have at maximum 4 characters):

aaaa
bbbb
bbbb
b
cc

Is this possible with sed, awk, grep or other tools in combination with a one-liner?

3
fold -w4 yourfile

Output

aaaa
bbbb
bbbb
b
cc
  • Unfortunately with current versions of GNU fold, that folds at 4 bytes (actually 4 columns (handling BS, CR and TAB at least), but failing to handle multi-byte (or zero-width or double-width) characters), not characters. – Stéphane Chazelas Mar 27 '17 at 18:44
  • But the OP wants a text file modified.... – user218374 Mar 27 '17 at 18:51
  • 2
    Yes, but see echo éééééé | fold -w 4 in a UTF-8 locale on a GNU system for instance. – Stéphane Chazelas Mar 27 '17 at 19:01
  • I used this solution, because this was the fastest. But the other solutions are also nice :) – kristian Mar 27 '17 at 21:21
3

Perl

perl -lne 'print for /.{1,4}|^$/g' yourfile

Sed1

sed -e '
   s/..../&\n/
   /\n$/P;//d
   P;D
' yourfile

Sed2

sed -e '
   s/..../&\n/g
   s/\n$//
' yourfile

Bash

while IFS= read -r l; do
   case $l in '' ) echo; continue ;; esac
   while case $l in '' ) break ;; esac; do
      echo "${l:0:4}"
      l=${l:4:${#l}}
   done
done < yourfile
2

All time classic grep:

$ echo "$a"
aaaa
bbbbbbbbb
cc

$ echo "$a" |egrep -o '(.){1,4}'
aaaa
bbbb
bbbb
b
cc
0
sed 's_\(....\).*_\1_' /path/to/input

Anything shorter than four characters won't be touched; anything longer will be truncated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.