如何使用简单的perl脚本重新排列txt文件的行



我的原始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] $kn";}' txt.txt

它起作用了,但我如何才能消除">

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

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

/r返回该值,而不是就地更改该值。

#!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 $lcln";
}
}
#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');

最新更新