命令 tr 上下提取

Command tr upper and lower extract

如果我想转换-字符之后的文本部分,比如 我可以使用 tr 命令吗?

使用此命令将函数应用于所有文本

cat file.txt | tr [: upper:] [: lower:]

01103I-GG102
01103I-GG102
01103I-GG102
01103I-GG102
01103I-HH'2
01103I-HH'2
01103I-HH'2
01103I-HH'2
01103I-HH'2
01103I-HH'2
01103I-HH'2
01103I-HH'2
01103I-HH'3
01103I-HH'12
01103I-HH'12
01103I-HH'12
01103I-HH'12
01103I-HH'12
01103I-HH'12
01103I-HH'12
01103I-HH'22
01103I-HH'22
01103I-HH'22
01103I-HH'42
01103I-HH'42
01103I-HH'42
01103I-HH'42
01103I-HH'42
01103I-HH'42
01103I-HH'43
01103I-GG62
01103I-GG62
01103I-GG62
01103I-GG62
01103I-GG62
01103I-GG62
01103I-GG62
01103I-GG62
01103I-GG63
01103I-GG63
01103I-GG63
01103I-GG63
01103I-GG63
01103I-GG63
01103I-GG63
01103I-GG52

你能帮帮我吗?

谢谢

如果我是你,我会选择 sed 解决方案。以下 sed 命令确实会按照 post 中的要求转换您的输入文件(在 - 之后变为小写)

$ sed 's/\(.*\)-\(.*\)/-\L/g' file
01103I-gg102
01103I-gg102
01103I-gg102
01103I-gg102
01103I-hh'2
01103I-hh'2
01103I-hh'2
01103I-hh'2
01103I-hh'2
01103I-hh'2
01103I-hh'2
01103I-hh'2
01103I-hh'3
01103I-hh'12
01103I-hh'12
01103I-hh'12
01103I-hh'12
01103I-hh'12
01103I-hh'12
01103I-hh'12
01103I-hh'22
01103I-hh'22
01103I-hh'22
01103I-hh'42
01103I-hh'42
01103I-hh'42
01103I-hh'42
01103I-hh'42
01103I-hh'42
01103I-hh'43
01103I-gg62
01103I-gg62
01103I-gg62
01103I-gg62
01103I-gg62
01103I-gg62
01103I-gg62
01103I-gg62
01103I-gg63
01103I-gg63
01103I-gg63
01103I-gg63
01103I-gg63
01103I-gg63
01103I-gg63
01103I-gg52

说明:

  • s/\(.*\)-\(.*\)/-\L/g 您在替换模式下使用 sed 并捕获 - 周围的 2 个组,然后您使用反向引用作为替换并将第二组转换为小写(包含之后的模式-) 使用 \L 选项。

tr用法:

如果你确定每一行的第二部分只有 HG 而它们没有出现在第一部分那么你可以想象像 tr 'HG...' 'hg...' 但这是这个 tr 命令所能做的最大的事情。

@Allan 的 sed 解决方案更好,但为了多样化,这里有另一种方法。

第一个 <(...) 内的部分提取破折号之前的部分。第二个<(...)里面的部分提取破折号后面的部分,用tr进行变换。 paste 然后重新组装这两个部分:

paste -d- <(cut -f1 -d- file.txt) <(cut -d- -f2 file.txt | tr [:upper:] [:lower:]) 

请注意,此技术是 "bashism",因此您需要使用 bash shell.


要获得更多变化,您也可以使用 awk

awk -F- '{=tolower()} 1' OFS=- file.txt

就是说... "Use dash (-) as the field separator. Change the letters in field 2 to lower case. Print the result - because awk's default action is to print if conditions are met, and as 1 evaluates to true, it prints."