简体   繁体   English

在bash中替换字符串中的字符

[英]Replace character in a string in bash

How can I replace two characters, 5th and 6th digit in the string below? 如何替换下面字符串中的第5位和第6位两个字符?

 2xxx99xx

I want to replace 5th and 6th digit (which is 99) by getting the record count of the file. 我想通过获取文件的记录数来替换第5位和第6位(即99)。

 $cat file | wc -l
 3

The output must be: 输出必须是:

 2xxx03xx
foo=2xxx99xx
printf "%s%02d%s" ${foo:0:4} $(wc -l < file) ${foo:6}

With sed: 与sed:

echo "2xxx99xx" | sed -r "s/(.{4})..(.*)/\1$(printf "%02d" `wc -l < ff`)\2/g"

first 4 characters form group 1, rest of the string except 5th and 6th characters form group 2. Then we put back the 1st group, formatted data, then the 2nd group. 前4个字符组成第1组,其余的字符串除外,第5个和第6个字符组成第2组。然后我们放回第一个组,格式化数据,然后放回第二组。

If the sed version doesn't support extended regex, use below command: 如果sed版本不支持扩展的正则表达式,请使用以下命令:

echo "2xxx99xx" | sed "s/\(.\{4\}\)..\(.*\)/\1$(printf "%02d" `wc -l < ff`)\2/g"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM