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
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
来源:https://stackoverflow.com/questions/18239636/add-n-after-a-specific-number-of-delimiters