Add '\n' after a specific number of delimiters

醉酒当歌 提交于 2019-12-13 12:39:57

问题


How can I add a \n after each four ; delimiter in a CSV file (with bash)?

Input file sample:

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

Output needed :

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

回答1:


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.




回答2:


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



回答3:


Perl solution:

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

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




回答4:


This might work for you (GNU sed):

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


来源:https://stackoverflow.com/questions/18239636/add-n-after-a-specific-number-of-delimiters

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