如何删除新的行字符,直到每行具有特定字符的特定数量的实例为止?

编程入门 行业动态 更新时间:2024-10-26 13:31:17
本文介绍了如何删除新的行字符,直到每行具有特定字符的特定数量的实例为止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个管道分隔文件,我需要加载到数据库的混乱。该文件有35个字段,因此有34个管道。其中一个字段由HTML代码组成,对于某些记录,它包括多个换行符。不幸的是,线路断开的地方没有模式。

I have a real mess of a pipe-delimited file, which I need to load to a database. The file has 35 fields, and thus 34 pipes. One of the fields is comprised of HTML code which, for some records, includes multiple line breaks. Unfortunately there's no patter as to where the line breaks fall.

我想出的解决方案是计算每条线路中的管道数,直到该数字达到34,从该行中删除新的行字符。我对Perl并不是非常精通,但我想我已经接近实现我想要做的事情。任何建议?

The solution I've come up with is to count the number of pipes in each line and until that number reaches 34, remove the new line character from that line. I'm not incredibly well-versed in Perl, but I think I'm close to achieving what I'm looking to do. Any suggestions?

#!/usr/local/bin/perl use strict; open (FILE, 'test.txt'); while (<FILE>) { chomp; my $line = $_; #remove null characters that are included in file $line =~ tr/\x00//; #count number of pipes my $count = ($line =~ tr/|//); #each line should have 34 pipes while ($count < 34) { #remove new lines until line has 34 pipes $line =~ tr/\r\n//; $count = ($line =~ tr/|//); print "$line\n"; } }

推荐答案

应该工作我猜。

#!/usr/bin/perl use strict; open (FILE, 'test.txt'); my $num_pipes = 0, my $line_num = 0; my $tmp = ""; while (<FILE>) { $line_num++; chomp; my $line = $_; $line =~ tr/\x00//; #remove null characters that are included in file $num_pipes += ($line =~ tr/|//); #count number of pipes if ($num_pipes == 34 && length($tmp)) { $tmp .= $line; print "$tmp\n"; # Reset values. $tmp = ""; $num_pipes = 0; } elsif ($num_pipes == 34 && length($tmp) == 0) { print "$line\n"; $num_pipes = 0; } elsif ($num_pipes < 34) { $tmp .= $line; } elsif ($num_pipes > 34) { print STDERR "Error before line $line_num. Too many pipes ($num_pipes)\n"; $num_pipes = 0; $tmp = ""; } }

更多推荐

如何删除新的行字符,直到每行具有特定字符的特定数量的实例为止?

本文发布于:2023-10-23 19:44:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521828.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   实例   数量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!