2017-10-10 122 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