[英]Format a file in Unix/Linux ?
我有一个包含国家,目录号,年份,描述和价格的文件
Kenya 563-45 1995 Heron Plover Thrush Gonolek Apalis $6.60
Surinam 632-96 1982 Butterfliers $7.50
Seychelles 831-34 2002 WWF Frogs set of 4 $1.40
Togo 1722-25 2010 Cheetah, Zebra, Antelope $5.70
文件不由“制表符”或“:”分隔。 它们之间只有空格。 你能告诉我如何格式化这个文件(使用awk?),我如何从中找到总价。
使用命令行perl:
$ cat /your/file | perl -e '$sum=0; for(<STDIN>) { $sum += $1 if(/\$([\d\.]+)/); }; print "$sum\n"'
21.2
和awk(假设你在每行结尾都有美元):
$ cat /your/file | awk '{s+=substr($NF,2)} END{ print s}'
21.2
另外,回应评论。 如果要在命令行上重新格式化:
$ cat /your/file | perl -e 'for(<STDIN>){@a=split /\s+/; $p=pop @a; \
$line=join "|", ($a[0],$a[1],$a[2], (join" ",@a[3..$#a]) ,$p); print "$line\n"}'
Kenya|563-45|1995|Heron Plover Thrush Gonolek Apalis|$6.60
Surinam|632-96|1982|Butterfliers|$7.50
Seychelles|831-34|2002|WWF Frogs set of 4|$1.40
Togo|1722-25|2010|Cheetah, Zebra, Antelope|$5.70
如果你想要正确地做到这一点,我不是在cmd行上做的,而是编写一个正确的程序来解析它。
我认为前3列和最后一列是固定含义但中间列不固定。 因此,中间列最后保留,其间有固定列,固定列由选项卡分隔,以便您可以使用某些电子表格程序开始编辑它:
awk '{ printf("%s\\t%s\\t%s\\t%s\\t", $1, $2, $3, $NF); for(i=4; i<NF; i++){ printf("%s ", $i); } printf("\\n") }' < yourlist.txt
为了符合 , regexp -fu解决方案:
$ perl -lne '/^ (.+?) \s+ (\d+-\d+) \s+ (\d{4}) \s+ (.+?) \s+ ( \$ ( \d+ (?:\.\d+)? ) ) \s* $/x and $t+=$6, print join "•",$1,$2,$3,$4,$5 }{ print $t' input_file
Kenya•563-45•1995•Heron Plover Thrush Gonolek Apalis•$6.60
Surinam•632-96•1982•Butterfliers•$7.50
Seychelles•831-34•2002•WWF Frogs set of 4•$1.40
Togo•1722-25•2010•Cheetah, Zebra, Antelope•$5.70
21.2
根据udslk的回答 , awk
肯定是你的朋友:
#!/usr/bin/env awk -f
BEGIN {
print "country, \"catalog number\", year, description, \"price ($)\""
}
{
description = $4
for (f = 5; f < NF; ++f) {
description = description " " $f
}
price = substr($NF, 2)
total += price
printf "\"%s\", \"%s\", \"%s\", \"%s\", %0.2f\n", $1, $2, $3, description, price
}
END {
printf "Total, , , , %0.2f\n", total
}
这会显示带有标题的CSV文件,您可以将其导入到您喜欢的电子表格中。 它还增加了总数。 根据品味切换带标签的逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.