将除特定行中每个单词的第一个字母之外的大写字母替换为小写字母

将除特定行中每个单词的第一个字母之外的大写字母替换为小写字母

我想替换仅以大写字母形式收到的名称。这些名称与其他信息混合在一起,应保持原样。AUTH:在该行的开头将其标识为应该替换名称的行。

TITLE: Average title
AUTH: SUPERMAN
AFF: Something
AUTH: THE NEW ONE
AFF: Berlin
AUTH: MARS-MENSCH
AFF: Planet Mars

那么应该是

TITLE: Average title
AUTH: Superman
AFF: Something
AUTH: The New One
AFF: Berlin
AUTH: Mars-Mensch
AFF: Planet Mars

我的问题与 Unix 问题相关但又不同”将西里尔字母大写中除第一个(大写)字母以外的所有字母小写“因为我使用罗马字母并且未能采用建议的解决方案。

为了获得相应的行,我使用egrep -rl ^"AUTH:"然后跟随| xargs sed -r -i '/(AUTH:)/ ??? /\1/g'我不知道用什么替换的地方???

答案1

> sed '/^AUTH/{s/^AUTH: //;s/\b\([[:alpha:]]\)\([[:alpha:]]*\)\b/\u\1\L\2/g;s/^/AUTH: /;}' file
TITLE: Average title
AUTH: Superman
AFF: Something
AUTH: The New One
AFF: Berlin
AUTH: Mars-Mensch
AFF: Planet Mars

答案2

sed -e '/^AUTH:\([^[:alpha:]]*\)/!b' -e 'h;s//\1/;x;s///                                                                  
    s/\([[:alpha:]]\)\([[:alpha:]]*[^[:alpha:]]*\)/\1/g;x;s//\
\2/g
    y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/;G;:l
    s/\n\(.*\n\)\(.\)/\2\1/;tl
    s/\(.*\)\n/AUTH:\1/
'<<\IN
TITLE: Average title
AUTH: SUPERMAN
AFF: Something
AUTH: THE NEW ONE
AFF: Berlin
AUTH: MARS-MENSCH
AFF: Planet Mars
AUTH: CONTRARY tO pOPULAR bELIEF, Lorem Ipsu'M is not simply random text. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance.                        
IN

要可移植地翻译字符,sed您需要使用y///translate 命令并明确设置要翻译的每个字符。这实际上确实很有用——这样就很少有混乱和/或猜测。

该脚本将每个授权:line 分成两位 - 将任何一个或多个字母字符系列中的第一个字母字符替换为 ewline \n。另一位只包含那些第一个字母,并且h在翻译该行时处于字段中。翻译后sed Gets 保留位,并用循环中\n最后一个 ewline 后面的第一个字符替换每个 ewline 字符,直到没有剩余。\n

这是l什么洛雷姆·伊普苏姆上面的行看起来就像在sed替换循环开始之前:

 \nontrary \no \nopular \nelief, \norem \npsum \ns \not \nimply \nand\
om \next. \norem \npsum \nomes \nrom \nections 1.10.32 \nnd 1.10.33 \
\nf "\ne \ninibus \nonorum \nt \nalorum" (\nhe \nxtremes \nf \nood \n\
nd \nvil) \ny \nicero, \nritten \nn 45 \nc. \nhis \nook \ns \n \nreat\
ise \nn \nhe \nheory \nf \nthics, \nery \nopular \nuring \nhe \nenais\
sance.\nCtpbLIinsrtLIcfsaodFBeMTEoGaEbCwiBTbiatottoevpdtR$

授权:当确认该行时,该位被剥离 - 它是最后重新插入的 - 所以它不在那里,但它后面的空格 - 以及之间可能出现的任何其他字符 - 都在那里。您可以看到所有单词都以\newlines 开头 -sed按顺序交换最后一个字符后面的字符串中的每个字符。sed保存每个单词的第一个字母时不区分大小写 - 它们都会被放在一边并稍后替换。

输出:

TITLE: Average title
AUTH: Superman
AFF: Something
AUTH: The New One
AFF: Berlin
AUTH: Mars-Mensch
AFF: Planet Mars
AUTH: Contrary to popular belief, Lorem Ipsu'M is not simply random text. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 Bc. This book is a treatise on the theory of ethics, very popular during the Renaissance.

答案3

使用最新版本的 GNU sed

sed -E '/^AUTH:/!b;s/([^\w:])(\w+)/\1\L\u\2/g'

对于旧版本:

sed -r '/^AUTH:/!b;s/([^[:alnum:]:])([[:alnum:]]+)/\1\L\u\2/g'

相关内容