如何在不删除 \n 的情况下删除 \r? [英] How do I remove \r without removing \n?

查看:75
本文介绍了如何在不删除 \n 的情况下删除 \r?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我会尽量让它变得简单.我现在正在格式化文件.这些是脚本应该完成的任务:

so I will try to make it as simple as possible. I am formatting files right now. These are the tasks that the script should complete:

  1. 删除\r\n
  2. 删除&
  3. #A 替换为 \n#A
  4. #D 替换为 \n#D
  1. delete \r\n
  2. delete &
  3. replace #A with \n#A
  4. replace #D with \n#D

我的代码已经可以工作了,但它还在添加的每个 \n 前面添加了 \r,这是我不想要的,因为 \r 不能被我想导入文件的程序识别.你知道一种只删除 \r 而不删除 \n 的方法吗?

My code is already working but it also adds \r in front on every \n added, and that's something I don't want because \r isn't recognized by the program I want to import my files to. Do you know a method to only delete \r without removing also the \n?

这是我的代码.我想只有最后一个 $data =~ s!\r!!g; 是相关的.为什么这不像预期的那样工作?每一行后面还有\r\n...

Here's my code. I guess only the last $data =~ s!\r!!g; is relevant. Why isn't this working like intented? There is still \r\n after every row...

opendir my $dir_a, $scriptdir or die "Kann Verzeichnis nicht oeffnen: $!";
my @stammdateien = grep { /root/ } readdir $dir_a;
closedir $dir_a;

foreach my $stammdatei (@stammdateien){
if ($stammdatei eq "root101" or $stammdatei eq "root112" or    $stammdatei eq "root116"){
    my $stammdateipfad = "$scriptdir\\$stammdatei";
    my $data = lese_file($stammdateipfad);
    $data =~ s!\r|\n!!g;
    $data =~ s!&!!g;
    $data =~ s!#A!\n#A!g;
    $data =~ s!#D!\n#D!g;
    $data =~ s!#M \| INSERT \|!#M \| UPDATE_INSERT \|!g;
    $data =~ s!\r!!g;
    schreibe_file($stammdateipfad, $data);  
}
}

sub lese_file {
my ($stammdatei) = @_;
open my $in, "<", $stammdatei or die "Konnte die Datei '$stammdatei' nicht zum lesen oeffnen: $!";
local $/ = undef;
my $all = <$in>;
close $in;
return $all;
}


sub schreibe_file {
my ($stammdateipfadout, $data) = @_;
my $outputdatei = "$stammdateipfadout"."_CONVERTED";
open my $out, ">", "$outputdatei" or die "Konnte die Datei $outputdatei nicht zum schreiben oeffnen: $!";
print $out $data;
close $out;
print "====> Vorgang abgeschlossen!\n\n";
return;
}

推荐答案

您使用的是 Windows 平台吗?默认 IO 层在 Windows 上将 \n 转换为 \r\n.要禁用它,请尝试以下之一:

Are you on a Windows platform? The default IO layer translates \n to \r\n on Windows. To disable that, try one of:

open my $out, ">", "$outputdatei" or ...;
binmode $out;

open my $out, ">:raw", "$outputdatei" or

这篇关于如何在不删除 \n 的情况下删除 \r?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆