Reputation: 85
I have a file with the following content:
string1_204
string2_408
string35_592
I need to get rid of string1_,string2_,string35_ and so on and add 204,408,592 to get a value. so the output should be 1204.
I can take out string1_ and string 2_ but for string35_592 I have 5_592. I cant seem to get the command right to do what I want to do. Please any help is appreciated:)
Upvotes: 1
Views: 975
Reputation: 47109
In case you are interested in a coreutils/bc alternative:
<infile cut -d_ -f2 | paste -sd+ - | bc
Output:
1024
cut
splits each line at underscore characters (-d_
) and outputs only the second field (-f2
). The column of numbers is passed on to paste
which joins them on a line (-s
) delimited by plus characters (-d+
). This is passed on to bc
which calculates and outputs the sum.
Upvotes: 3
Reputation: 158020
With awk:
awk -F_ '{s+=$2}END{print s}' your.txt
Output:
1204
Explanation:
-F_ sets the field separator to _ what makes it easy to access
the numbers later on
{
# runs on every line of the input file
# adds the value of the second field - the number - to s.
# awk auto initializes s with 0 on it's first usage
s+=$2
}
END {
# runs after all input has been processed
# prints the sum
print s
}
Upvotes: 5