使用 bash 替换文件本身特定位置的字母

substitute a letter at a specific position in the file itself using bash

我正在尝试这样做:

我有一个文件,内容如下;

文件: abcdefgh

我正在寻找一种方法来做到这一点;

文件: aBCdefgh

所以,在文件本身中制作第二个和第三个字母“capital/uppercase,因为我必须这样做多次转换 在文件中字符串的不同位置。有人可以帮我知道该怎么做吗?

我在下面了解到类似这样的内容,但它仅适用于文件中字符串的第一个字符:

sed -i 's/^./\U&/' file

输出: Abcdefgh

非常感谢!

awk值班

echo "abcdefgh" | awk '{print substr([=10=],1,1) toupper(substr([=10=],2,2)) substr([=10=],4)}'

输出结果如下。

aBCdefgh

如果您有一个 Input_file 并且您想要将编辑保存到相同的 Input_file。

awk '{print substr([=12=],1,1) toupper(substr([=12=],2,2)) substr([=12=],4)}'  Input_file  > temp_file && mv temp_file  Input_file

解释:请运行上面的代码,因为这仅用于解释目的。

echo "abcdefgh"  ##using echo command to print a string on the standard output.
|                ##Pipe(|) is used for taking a command's standard output to pass as a standard input to another command(in this case echo is passing it's standard output to awk).
awk '{           ##Starting awk here.
                 ##Print command in awk is being used to print anything variable, string etc etc.
                 ##substring is awk's in-built utility which will allow us to get the specific parts of the line, variable. So it's syntax is substr(line/variable,starting point of the line/number,number of characters you need from the strating point mentioned), in case you haven't mentioned any number of characters it will take all the characters from starting point to till the end of the line.
                 ##toupper, so it is also a awk's in-built utility which will covert any text to UPPER CASE passed to it, so in this case I am passing 2nd and 3rd character to it as per OP's request.
print substr([=13=],1,1) toupper(substr([=13=],2,2)) substr([=13=],4)}'

将您的 sed 方法更改为以下内容:

sed -i 's/\(.\)\(..\)/\U/' file

$ cat file
aBCdefgh

匹配部分:

  • \(.\) - 将字符串的第一个字符匹配到第一个捕获组

  • \(..\) - 匹配放入第二个捕获组的接下来的 2 个字符

替换节:

  • </code> - 指向第一个带括号的组 <code> 即第一个字符

  • \U - 将第二个捕获组中的字符大写 </code></p></li> </ul> <hr> <p><strong>奖励</strong> <em>方法我想将“第 105 和 106”字符大写</em>:</p> <pre><code>sed -Ei 's/(.{104})(..)/\U/' file