Add '\ n' after a certain number of delimiters

How to add \nafter each four separators ;in a CSV file (with bash)?

Example input file:

aaaa;bbbbbb;cccc;ddddd;eeee;ffff;gggg;hhhh;iii;jjjj;kkkk;llll;

Necessary conclusion:

aaaa;bbbbbb;cccc;ddddd
eeee;ffff;gggg;hhhh
iii;jjjj;kkkk;llll
+2
source share
4 answers

Usage (GNU) sed:

... | sed -r 's/([^;]*;){4}/&\n/g'

[^;]*; matches a sequence of characters that are not semicolons, and then a semicolon.

(...){4} matches a 4-fold expression inside parentheses.

& in replacement is the complete match that was found.

\n is a newline character.

g sed , .

+3

, 4 printf , .

while IFS=';' read -a line; do
    printf '%s;%s;%s;%s\n' "${line[@]}"
done < input.txt
+2

Perl Solution:

perl -pe 's/;/++$i % 4 ? ";" : "\n"/ge; chomp'

It works only if the number of fields is divided by four.

+1
source

This may work for you (GNU sed):

sed 's/;/\n/4;/./P;D' file
0
source

Source: https://habr.com/ru/post/1541183/


All Articles