JackWM
JackWM

Reputation: 10535

Break a one-line file to a multi-line file, each line with the same number of words?

E.g. One-line file line.txt has the following line:

741 12 3 24 45 123 32 111 34

Suppose specifying the number of words in each is 3. then the goal is:

741 12 3
24 45 123
32 111 34

What scripts could help in this case, a simple one would be appreciated.

Upvotes: 1

Views: 87

Answers (5)

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

Try this

printf "%s %s %s\n" $(cat line.txt)

It yields

741 12 3
24 45 123
32 111 34

Upvotes: 2

jfg956
jfg956

Reputation: 16740

cat your_file | tr " " "\n" | paste -s -d "  \n"

Upvotes: 2

Thomas
Thomas

Reputation: 17412

Here's a way using sed. With the number of words fixed to 3, you could do:

sed 's/\( [^ ]* [^ ]*\) /\1\n/g' <filename>

If you want to dynamically specify the number of words, you can create the regexp on the fly with the following script:

#!/bin/sh

test $# -eq 2 || (echo "Usage: $(basename "${0}") <filename> <#words>" && exit 1)

for i in $(seq 2 "${2}"); do
    REGEX=" [^ ]*${REGEX}"
done

cat "${1}" | sed "s/\\(${REGEX}\\) /\\1\n/g"

Upvotes: 1

Birei
Birei

Reputation: 36262

One way using awk:

awk '{ 
  for ( i = 1; i <= NF; i++ ) { 
    printf "%s%s", $i, (i % 3 == 0) ? "\n" : " " 
  } 
}' line.txt

It yields:

741 12 3
24 45 123
32 111 34

EDIT to fix the script (see comments) for a number of fields not multiple of 3:

awk '
  { 
    for ( i = 1; i <= NF; i++ ) { 
      printf "%s%s", $i, (i < NF && i % 3 == 0) ? "\n" : " " 
    } 
  } 
  END { printf "\n" }
' infile

Upvotes: 1

Kent
Kent

Reputation: 195039

this would be a easy job for awk. I saw the question with vim too, then tried it a bit with vim.

Assume that the cursor is at the beginning of the line. You could try to type (in NORMAL mode):

100@='3f r^M'

then type Enter.

The macro can be recorded by qn3f r<Enter>q too, then you just 100@n

Note

  • the ^M you need to type <C-V><Enter>
  • I didn't calculate how many times you should do the macro, so just gave 100. If the result would be more than 100 lines, you just give 500, or 1000. :)
  • If the given number has problem, e.g. the line cannot be divided by 3, then the last line could contain columns less than the given number. e.g. 3.

Upvotes: 5

Related Questions