bash - 按长度替换模式(Bash 的可移植解决方案)

标签 bash perl awk sed

有没有一种方法可以用 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+)/长度($1)/e'?

最佳答案

用长度替换第一个模式:

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

输出:

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

关于bash - 按长度替换模式(Bash 的可移植解决方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958797/

相关文章:

linux - Centos 7,未找到 ImageMagick 命令

bash - 在 stdout 上打印 n 行 "command' s --help"

perl - Perl 中的 Sprintf 无法正确显示十六进制字符

regex - awk 树桩 : regex substitution within a field

Bash:按字符串调用数组项

linux - 是否存在默认未安装 Perl 的 Unix 平台?

perl - 范围对象在 Excel 中的位置

linux - 使用 awk 或 sed 提取两者中的详细信息

linux - 如何使用 linux 命令在一行中的偶数位置用点替换空格

linux - 我如何在 Windows 上运行 Ubuntu 的/bin/bash