【问题标题】:How to rearrange the row of my txt file using simple perl script? [closed]如何使用简单的 perl 脚本重新排列我的 txt 文件的行? [关闭]
【发布时间】:2020-04-13 18:25:58
【问题描述】:

我原来的txt文件是这样的:

A "a,b,c"
B "d"
C "e,f"

如何将其转换为:

A a
A b
A c
B d
C e
C f

我试过了

perl -ane '@s=split(/\,/, $F[1]); foreach $k (@s){print "$F[0] $k\n";}' txt.txt

它有效,但我怎样才能消除“”

【问题讨论】:

  • 你试过什么?它是如何失败的?
  • 很抱歉之前没有提到这个!
  • 是否有转义机制,或者像Foo "Bar" Baz 这样的值根本无法保存?

标签: perl parsing text-parsing


【解决方案1】:

您可以使用替换来删除双引号

@s = split /,/, $F[1] =~ s/"//gr;

/r 返回值而不是在原地更改值。

【讨论】:

    【解决方案2】:
    #!usr/bin/perl
    
    #Open files
    open(FH,'<','rearrange letters.txt');
    open(TMP, '>','temp.txt');
    # A "a,b,c"
    # B "d"
    # C "e,f"
    #<----This extra new line is necessary for this code to run
    while(chomp($ln=<FH>)){
        #Get rid of double quotes
        $ln=~s/\"//g;
        #Take out the non quoted first character and store it in a scalar variable
        my @line = split(' ',$ln);
        my $capletter = shift @line;
        #split the lower case characters and assign them to an array
        my @lowercaselist = split(',',$line[0]);
        #Iterate through the list of lower case characters and print each to the temp file preceded by the capital character
        for my $lcl(@lowercaselist){
            print TMP "$capletter $lcl\n";
        }
    }
    #Close the files
    close(FH);
    close(TMP);
    #Overwrite the old file with the temp file if that is what you want
    rename('temp.txt','rearrange letters.txt');
    

    【讨论】:

    • 我想这是很长的路
    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 2020-10-31
    • 2016-08-02
    • 1970-01-01
    • 2013-06-19
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多