CentOS 7 find 查找文件与 sed 替换修改
通过使用find命令查找文件,用管道|加xargs命令,交给sed命令替换修改文件的内容,可以达到批量处理文件的效果。
一、答题
题目:把/boy目录及其子目录下,所有以扩展名.sh结尾的文件,包含boy的字符串全部替换为girl。
创建环境,执行如下命令:
mkdir -p /boy/testcd /boyecho "boy">test/del.shecho "boy">test.shecho "boy">t.shtouch boy.txttouch hello.txt
使用pwd命令,查看是否在/boy目录下。使用find命令,查看当前目录下(包括子目录)的所有信息。
[root@centos7 boy]# pwd/boy[root@centos7 boy]# find../test./test/del.sh./hello.txt./t.sh./boy.txt./test.sh[root@centos7 boy]#
其中.代表当前目录。
二、解题
第一步,找出文件。
使用find命令,在/boy目录下查找扩展名以.sh结尾的文件。
[root@centos7 boy]# find /boy -type f -name "*.sh"/boy/test/del.sh/boy/t.sh/boy/test.sh
第二步,把 boy 替换为 girl 。
为了避免错误,先只处理一个文件,用于查看效果。使用sed命令,替换字符串。
# 查看文件内容为 boy[root@centos7 boy]# cat /boy/test.shboy# 执行替换为 girl[root@centos7 boy]# sed 's#boy#girl#g' /boy/test.shgirl# 再次查看文件内容为 boy[root@centos7 boy]# cat /boy/test.shboy
其中sed命令的's#boy#girl#g'参数表示为,把字符串boy替换为girl,参数中的井号#可以是任意字符,但必须保持一致,例如's@boy@girl@g'。
可以看到,执行替换后,文件内容并没有修改。下面我们添加sed命令参数-i修改文件内容。
[root@centos7 boy]# cat /boy/test.shboy[root@centos7 boy]# sed -i 's#boy#girl#g' /boy/test.sh[root@centos7 boy]# cat /boy/test.shgirl
可以看到,已经成功修改/boy/test.sh文件内容为girl。
第三步,修改替换全部文件。
把find命令找到的文件,通过管道|加xargs命令,交给sed命令处理。
首先,查看执行效果,sed命令不带-i参数。
[root@centos7 boy]# find /boy -type f -name "*.sh"|xargs sed 's#boy#gril#g'grilgrilgirl
检查没问题后,执行替换修改。sed命令带上-i参数。
[root@centos7 boy]# find /boy -type f -name "*.sh"|xargs sed -i 's#boy#gril#g'# 使用 cat 命令查看全部文件内容[root@centos7 boy]# find /boy -type f -name "*.sh"|xargs catgrilgrilgirl
到此,完成。
(完)