2017-10-10 153 views
-1

我试图做到这一点在文件本身在特定位置的一封信:替代使用bash

我有类似下面内容的文件;

文件: ABCDEFGH

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

文件: 一个BC defgh

因此,使第二和第三个字母“资本/大写文件本身的,因为我要做多次转换在不同的位置在文件中的字符串中。有人可以帮助我知道如何做到这一点?

我才知道这样的事情下文,但它仅适用于文件中的字符串的一个第一个字符:

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

输出: ABCDEFGH

谢谢了!

回答

1

更改的sed方法如下:

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

$ cat file 
aBCdefgh 

匹配部分:

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

  • \(..\) - 匹配下一个2个字符放置到第二捕获组

替换部分:

  • \1 - 指向第一个括号中的组\1即第1字符

  • \U\2 - 大写的从第二捕获组\2


奖金方法的字符我想利用 “105 &第106” 字

sed -Ei 's/(.{104})(..)/\1\U\2/' file 
+0

''^是多余的,第一场比赛左开始和'.'将始终与第一炭 – 123

+0

谢谢!你能帮我理解命令吗? :-)。例如;我不明白只有“bc”被大写。 – Dipak

+0

@Dipak,看我的解释 – RomanPerekhrest

1

awk值班。

echo "abcdefgh" | awk '{print substr($0,1,1) toupper(substr($0,2,2)) substr($0,4)}' 

输出如下。

aBCdefgh 

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

awk '{print substr($0,1,1) toupper(substr($0,2,2)) substr($0,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($0,1,1) toupper(substr($0,2,2)) substr($0,4)}' 
+1

短简洁。我喜欢! –

+0

@MatiasBarrios,欢迎您。感谢您的鼓励。 – RavinderSingh13

+0

谢谢!你能帮我理解命令在做什么吗? – Dipak