Reputation: 10535
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
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
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
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
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
^M
you need to type <C-V><Enter>
Upvotes: 5