【面试题】 查找文件中1到20行之间,同时将"aaa"替换为"AAA","ddd"替换"DDD"

老男孩教育oldboyedu.com.png

运维学习交流群-点我加群:598972270

[root@oldboyedu59 ~]# cat /oldboy/lidao.txt

a b c d e f g h i j k l m n o p q r s t u v w x y z

aaadddaaaddd

aaadddaaaddd

aaadddaaaddd

思路1:简单的替换aaa替换为AAA,ddd替换为DDD

awk 'NR==1,NR==20{gsub(/aaa/,"AAA");gsub(/ddd/,"DDD")}1' lidao.txt
sed '1,20{s#aaa#AAA#g;s#ddd#DDD#g}' lidao.txt

方法1-awk进行替换

[root@oldboyedu-show01 ~]# awk 'NR==1,NR==20{gsub(/aaa/,"AAA");gsub(/ddd/,"DDD")}1' lidao.txt

a b c d e f g h i j k l m n o p q r s t u v w x y z

AAADDDAAADDD

AAADDDAAADDD

AAADDDAAADDD

方法2-sed进行替换

[root@oldboyedu-show01 ~]# sed '1,20{s#aaa#AAA#g;s#ddd#DDD#g}' lidao.txt

a b c d e f g h i j k l m n o p q r s t u v w x y z

AAADDDAAADDD

AAADDDAAADDD

AAADDDAAADDD

思路2:大小写转换,把小写字母转换为大写字母

tr 'ad' 'AD' sed 'y/ad/AD/' lidao.txt
awk '{print toupper($0)}' lidao.txt
sed 's#[ad]#\U&#g' lidao.txt

方法1-tr

[root@oldboyedu-show01 ~]# tr 'ad' 'AD' 

方法2-sed

[root@oldboyedu-show01 ~]# sed 'y/ad/AD/' lidao.txt

A b c D e f g h i j k l m n o p q r s t u v w x y z

AAADDDAAADDD

AAADDDAAADDD

AAADDDAAADDD

说明:
sed命令中y/// 类似于tr1对1替换,但是不能使用a-z A-Z范围

方法3-awk函数

[root@oldboyedu-show01 ~]# awk '{print toupper($0)}' lidao.txt

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

AAADDDAAADDD

AAADDDAAADDD

AAADDDAAADDD

方法4-sed 中的\U大小写转换

[root@oldboyedu-show01 ~]# sed 's#[ad]#<&>#g' lidao.txt

 b c  e f g h i j k l m n o p q r s t u v w x y z







[root@oldboyedu-show01 ~]# sed 's#[ad]#\U&#g' lidao.txt

A b c D e f g h i j k l m n o p q r s t u v w x y z

AAADDDAAADDD

AAADDDAAADDD

AAADDDAAADDD

思路3:1 到20 大小写转换,把小写字母转换为大写字母

sed -n '1,20p' lidao.txt| tr 'ad' 'AD'
awk 'NR==1,NR==20{print toupper(0)}' lidao.txt
sed '1,20s#[ad]#\U&#g' lidao.txt
sed '1,20y/ad/AD/' lidao.txt

你可能感兴趣的:(【面试题】 查找文件中1到20行之间,同时将"aaa"替换为"AAA","ddd"替换"DDD")