Add '\\n' after a specific number of delimiters

荒凉一梦 提交于 2019-12-06 14:21:32

Using (GNU) sed:

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

[^;]*; matches a sequence of characters that are not semicolons followed by a semicolon.

(...){4} matches 4 times the expression inside the parentheses.

& in the replacement is the whole match that was found.

\n is a newline character.

The modifier g make sed replace all matches in each input line instead of just the first match per line.

Read each line into an array, then print 4 groups at a time with printf until the line is exhausted.

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

Perl solution:

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

Only works if the number of fields is divisible by four.

This might work for you (GNU sed):

sed 's/;/\n/4;/./P;D' file
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!