简体   繁体   English

如何仅更改单词中的特定字母Bash脚本

[英]How to change only specific letters within a word us bash scripting

I have a file that contains addresses like: 我有一个包含如下地址的文件:
0x0003ffff
0x0003ffff
0x0000ffff
0x0000ffff
0x003fffff
0x05ffffff
0x3fffffff
0x000000ff There can be 'n' number of such addresses in that file , i want the addresses changed to 0x000000ff该文件中可以有'n'个这样的地址,我希望将地址更改为

0x0003FFB0
0x0003FFB0
0x0000FFB0
0x0000FFB0
0x003FFFB0
0x05FFFFB0
0x3FFFFFB0
0x000000B0 For all the 'n' addresses. 0x000000B0对于所有“ n”地址。 What i basically want is to change the last 2 'ff's into 'B0' and the remaining 'f's into 'F' How can i do that using bash scripting? 我基本上想要的是将最后2个'ff's更改为'B0',将其余的'f's更改为'F'我该如何使用bash脚本做到这一点?

Use sed: 使用sed:

sed --in-place 's/\(0x000[0-9]\)ffff/\1FFB0/' file

Try it without the --in-place flag first to make sure it's what you want. 请先尝试使用--in-place标志,以确保它是您想要的。

In case, like Nikhilesh Sharma pointed out, you might have more F's than indicated in your question, you can use the following. 如果像Nikhilesh Sharma指出的那样,如果您的F可能比问题中指出的要多,则可以使用以下内容。 I'm assuming you have GNU sed. 我假设您已使用GNU sed。 Let me know if this doesn't work and I'll give you the longer, but posix friendly, version. 让我知道这是否行不通,我将为您提供更长的版本,但对posix友好。

sed --in-place 's/\(0x[0-9f]\{6\}\)ff/\U\1B0/' file

Here's a good tutorial to cut your teeth on sed. 这是一个很好的教程,可以让您在sed上大吃一惊。

Assuming that: 假如说:

  1. your input file is called input.txt 您的输入文件称为input.txt
  2. all addresses start at column 1 所有地址都从第1列开始
  3. you want to keep the first 8 characters 您想保留前8个字符
  4. all addresses end with ff 所有地址都以ff结尾

then this could work (at least it works for your input): 那么这可以工作(至少对您的输入有效):

cat input.txt | cut -b1-8 | tr f F | sed s/$/B0/g

If you have gawk, use numeric operations instead of string operations 如果您有gawk,请使用数字运算而不是字符串运算

gawk '
  {n = strtonum($1)} 
  (n % 0x100) == 0xff {printf("0x%08X\n", n - 0x4f)}
'

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

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