I have a file of strings:
我有一个字符串文件:
XC:a:1
XC:b:2
XC:c:0
and so on. I want to split it at the second :
and sum all the integers. For example, for the above list I want to do 1+2+0+...
等等。我想把它分成两部分,把所有的整数相加。例如,对于上面的列表,我想做1+2+0+…
I tried cut -d ":"
but it gives only the field XC
.
我试过cut -d:“但它只给出字段XC。”
4 个解决方案
#1
1
If you have perl installed; you could do this in one line.
如果您安装了perl;你可以在一条直线上做这个。
perl -F/:/ -ane 'END {print "$x\n"} $x += $F[2]' inputFile
-F/:/ sets colon as the split separator works with -a
-a autosplit mode with -n splits each line into @F
-n assume "while (<>) { ... }" loop around program
#2
1
You can use cut
and paste
this way:
你可以这样剪切和粘贴:
paste -s -d+ <(cut -f3 -d: file) | bc
-
<(cut ...)
=> uses process substitution to send the extracted numbers topaste
- <(cut…)=>使用过程替换将提取的数字发送给粘贴。
-
paste -s -d+
=> converts numbers on multiple lines to this format1+2+3
which is then fed tobc
for math - 粘贴-s -d+ =>将多行上的数字转换为这种格式1+2+3,然后输入bc进行数学运算
#3
0
This can be done using awk, try this one or you can replace $NF with the column number.
这可以使用awk完成,试试这个,或者可以用列号替换$NF。
awk -F: '{sum+=$NF} END { print sum}' file_name
awk -F: '{sum+=$NF}结束{print sum}' file_name
#4
0
Using Python:
使用Python:
python -c "print(sum(int(line.split(':')[-1]) for line in open('filename')))"
#1
1
If you have perl installed; you could do this in one line.
如果您安装了perl;你可以在一条直线上做这个。
perl -F/:/ -ane 'END {print "$x\n"} $x += $F[2]' inputFile
-F/:/ sets colon as the split separator works with -a
-a autosplit mode with -n splits each line into @F
-n assume "while (<>) { ... }" loop around program
#2
1
You can use cut
and paste
this way:
你可以这样剪切和粘贴:
paste -s -d+ <(cut -f3 -d: file) | bc
-
<(cut ...)
=> uses process substitution to send the extracted numbers topaste
- <(cut…)=>使用过程替换将提取的数字发送给粘贴。
-
paste -s -d+
=> converts numbers on multiple lines to this format1+2+3
which is then fed tobc
for math - 粘贴-s -d+ =>将多行上的数字转换为这种格式1+2+3,然后输入bc进行数学运算
#3
0
This can be done using awk, try this one or you can replace $NF with the column number.
这可以使用awk完成,试试这个,或者可以用列号替换$NF。
awk -F: '{sum+=$NF} END { print sum}' file_name
awk -F: '{sum+=$NF}结束{print sum}' file_name
#4
0
Using Python:
使用Python:
python -c "print(sum(int(line.split(':')[-1]) for line in open('filename')))"