awk或sed删除带有字符串和数字的图案

awk或sed删除带有字符串和数字的图案,awk,Awk,我有一个包含以下内容的文件: string1_204 string2_408 string35_592 我需要去掉string1、string2、string35等等,然后加上204408592得到一个值。 所以输出应该是1204 我可以取出弦1和弦2,但对于弦35,我有5。 我似乎不能得到正确的命令去做我想做的事。感谢您的帮助:使用awk: awk -F_ '{s+=$2}END{print s}' your.txt 输出: 1204 1024 说明: -F_ sets the

我有一个包含以下内容的文件:

string1_204
string2_408
string35_592
我需要去掉string1、string2、string35等等,然后加上204408592得到一个值。 所以输出应该是1204

我可以取出弦1和弦2,但对于弦35,我有5。 我似乎不能得到正确的命令去做我想做的事。感谢您的帮助:

使用awk:

awk -F_ '{s+=$2}END{print s}' your.txt 
输出:

1204
1024
说明:

-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
}
使用awk:

awk -F_ '{s+=$2}END{print s}' your.txt 
输出:

1204
1024
说明:

-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
}

如果您对coreutils/bc备选方案感兴趣:

<infile cut -d_ -f2 | paste -sd+ - | bc
说明:
cut在下划线字符-d_处分割每一行,并仅输出第二个字段-f2。数字列被传递到paste,paste将它们连接到一行-s上,该行由加号-d+分隔。这将传递给bc,bc计算并输出总和。

如果您对coreutils/bc替代方案感兴趣:

<infile cut -d_ -f2 | paste -sd+ - | bc
说明:
cut在下划线字符-d_处分割每一行,并仅输出第二个字段-f2。数字列被传递到paste,paste将它们连接到一行-s上,该行由加号-d+分隔。这将传递给bc,由bc计算并输出总和。

相当隐晦,但现在我知道@newtover:我发现它更可读,更容易用这种方式编辑。相当隐晦,但现在我知道@newtover:我发现它更可读,更容易用这种方式编辑。