我想在每个单词的第一个字符加上括号
$ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g'
有人可以解释吗?我不知道它是如何工作的?
答案 0 :(得分:1)
sed 's/pattern1/pattern2' --- Does "replace first occurrence of pattern1 with pattern2"
sed 's/pattern1/pattern2/g' --- Does "A (g)lobal replacement => replace all the occurrence of pattern1 with pattern2 "
sed 's/\b(pattern1)/pattern2/g' --- Does " A word by word search"
sed 's/\b([A-Z])/pattern2/g' --- Does " Matches a single uppercase letter"
sed 's/\b([A-Z])/(\1)/g' --- Does " sed 's/\b([A-Z])/([A-Z])/g' "
\1 is a back reference. [Refer][https://www.gnu.org/software/sed/manual/html_node/Back_002dreferences-and-Subexpressions.html]
简而言之,它会用(大写字母)逐字搜索来对所有大写字母进行全局替换(替换所有出现的字母)。
答案 1 :(得分:1)
我需要使用sed -E
才能正常工作。
$ echo "Welcome To The Geek Stuff" | sed 's/(\b[A-Z])/(\1)/g'
sed: -e expression #1, char 18: invalid reference \1 on `s' command's RHS
$ echo "Welcome To The Geek Stuff" | sed -E 's/(\<.)/(\1)/g'
(W)elcome (T)o (T)he (G)eek (S)tuff
您还可以使用\<
锚点,它是“单词的开头”,其中\b
是“单词边界”。使用单词开始标记可以简化正则表达式以匹配任何单词字符:
$ echo "Welcome To The Geek Stuff 123" | sed -E 's/\<./(&)/g'
(W)elcome (T)o (T)he (G)eek (S)tuff (1)23
答案 2 :(得分:0)
您应该这样做:
echo "Welcome To The Our Class" | sed 's/\([A-Z]\)/\(\1\)/g'
(删除“ \ b”) 在第一个“ /”至第二个“ /”至第二个之间,有一个要替换的表达式。 您在句子中搜索一个以大写字母开头的字符串(chr在A到Z之间),并在此字母前加上“(”,之后是“)”。 1表示单词中的第一个字母。 输出将是:
(W)elcome (T)o (T)he (O)ur (C)lass
答案 3 :(得分:0)
要将单词的前 3 个字母括起来,可以使用
<块引用>$ echo "敏捷的棕色狐狸跳过一只懒惰的狐狸 dog" | sed 's/(\b[a-Z]{1,3})/(&)/g' (the) (qui)ck (bro)wn (fox) (jum)ps (ove)r (a) (laz)y (dog) $