首页 > 解决方案 > 用长度替换模式(Bash 的便携式解决方案)

问题描述

有没有办法用 Sed/Awk/Perl 用它的长度替换一个模式?我正在寻找可以在 Bash 脚本中使用的小型便携式命令。

我有所有以特定字符开头的字符串(比如说x),我想x用它们的长度替换这些重复。

所以

xxxx rest of the line
xxx again
xx again and again
xxxxx you got my point

会成为

4 rest of the line
3 again
2 again and again
5 you got my point

Sed 可能不是一个好的候选人。我知道 Perl 有一个e允许在替换字符串中执行代码的选项,但我不确定在这里如何使用它:perl -pe 's/^(x+)/length($1)/e'

标签: bashperlawksed

解决方案


用它的长度替换第一个模式:

awk '$1=length($1)' file

输出:

其余 4 条线路
3再
2一次又一次
5 你明白我的意思

推荐阅读