-1

I need to concatenate the line with next line if the line char count is less than x chars.

closed as unclear what you're asking by Drav Sloan, chaos, Archemar, Ramesh, cuonglm Aug 5 '15 at 16:30

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    welcomme to U&L. Can you edit your post with what you have tried ? – Archemar Aug 5 '15 at 12:44
  • can be improved: awk 'length < 3 { printf "%s ", $0; next }1' file – llua Aug 5 '15 at 12:49
  • 2
    And if after concatenation, the line is still less than x chars, do you want to concatenate the next line again? – Stéphane Chazelas Aug 5 '15 at 13:10
  • Yes. We have to check the length of the line after concatenation to make sure all the lines have the same length. The file should be a fixed width (each record should be fit in a single file) but, sometimes the single record spanned into multiple lines due to bad data (new line characters in data ). – user161709 Aug 5 '15 at 17:05
0

Using GNU sed

Input

flood
good
good
good
good
good
flood
good
good

If you want the newly concatenated line to count against the number of chars

sed ':;/.\{5,\}$/!{N;s/\n/ /g;b}'

flood
good good
good good
good flood
good good
good

If you want to count each line on its own and concatenate each line that is less to the previous

sed ':;/[^\n]\{5,\}$/!{N;$!b};s/\n/ /g'

flood
good good good good good flood
good good good
  • That is GNU specific. : requires a label. And traditional implementations (and the current version of the POSIX spec) allow any char in the label name (so :;/... would define a label called ;/...). b without a label is meant to branch to the end. [^\n] matches anything but backslash and n in most sed implementations. } and b cannot be followed by any other command. – Stéphane Chazelas Aug 5 '15 at 13:52
  • @StéphaneChazelas There you go :) – 123 Aug 5 '15 at 13:57
0
$ n=20
$ seq 40 | sed -e :1 -e "/.\{$n\}/!{N;s/\n//;b1" -e '}'
123456789101112131415
16171819202122232425
26272829303132333435
3637383940

Or to join lines so that they are up to 20 chars (as opposed to at least 20 chars):

$ seq 40 | fmt -w 20
1 2 3 4 5 6 7 8
9 10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 25 26
27 28 29 30 31 32
33 34 35 36 37 38
39 40

$ seq 40 | par -w20
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
32 33 34 35 36 37 38
39 40
  • Isn't the second keeping lines under a certain number of chars, rather than ensuring they they are at least that many ? – 123 Aug 5 '15 at 13:17
  • @User112638726, yes, I guess I should that make clear. – Stéphane Chazelas Aug 5 '15 at 13:43

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