简体   繁体   中英

How do I use sed to capitalize the last instance in each line of a word that starts with “/”?

I'm trying to capitalize every word that starts with "/" while ignoring the same word that doesn't start with "/" using sed. So for example, if the output has

word1
/word1

I want to leave the first word1 untouched and capitalize the second word1 to become

word1
/WORD1

If the file has multiple word1 in the same line, I want it to capitalize the last instance of word1 so

word1 /word1 /word1

would become

word1 /word1 /WORD1

I have tried sed 's/word1/\\U&/' but it simply capitalizes the every word1 in the file and I'm not quite sure how to include "/" in the search string as it would just throw an error if I add it straight on.

https://www.gnu.org/software/sed/manual/html_node/The-_0022s_0022-Command.html

"The / characters may be uniformly replaced by any other single character within any given s command. The / character (or whatever other character is used in its stead) can appear in the regexp or replacement only if it is preceded by a \\ character. "

https://www.gnu.org/software/sed/manual/html_node/Regexp-Addresses.html#Regexp-Addresses "/regexp/

This will select any line which matches the regular expression regexp. If regexp itself includes any / characters, each must be escaped by a backslash (\). "

I don't got any experience using sed, but it seems to me as you can use regex to concretely specify patterns which you want to get capitalized. In the regex expressions you can use the character "/", but you need to escape it with a backslash. So try something like

sed 's/word1/\\U&/' (I'm not quite sure where the backslash needs to be put, but by this and trying around you should be able to give the regular expression of your word with the escaped "/" before and only this word should be capitalized.

As can be seen at https://ideone.com/htALOt --

sed -Ee 's@(.*)(/word1)@\1\U\2@'

The (.*) matches as much as possible from the beginning, which is reproduced unchanged when \\1 is encountered. \\U tells GNU sed to start making replacements in all-uppercase, and \\2 then writes that content in all-caps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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