Search Suggest

Shell - Search và Replace trong file

1. Tìm kiếm file với lệnh find

 find <search dir> -type <file or dir> -name <pattern file name>  

Ex:
find /home/user/Downloads -type f -name "*.rar"
Tìm kiếm tất cả các file nén .rar trong thư mục Downloads

2. Tìm kiếm và thay thế string trong một file với lệnh sed

 sed -i "s:<string to search>:<string to replace>:" infile outfile   
or
sed -i "s:<string to search>:<string to replace>:" filename
# tim, thay the va save filename

Ex:
sed -i "s:day:night:" testfile.txt


3. Tìm kiếm file, search và thay thế nội dung file với sự kết hợp của findsed

 #!/bin/sh  

# Tao listfile.txt luu danh sach tat ca cac file trong thu muc Downloads
#find /home/ninhld/Downloads -type f -name '*' > /home/ninhld/Downloads/listfile.txt

#Duyet qua tat ca cac file trong thu muc Downloads, search va replace tat ca
#cac file ma noi dung co noi dung /home/ninhld/Downloads
FINDPATH="/home/ninhld/Downloads"
FILETYPE="*"
PATTERN="/home/ninhld/Downloads"
REPLACE=""

find $FINDPATH -type f -name "$FILETYPE" -exec sed -i "s:$PATTERN:$REPLACE:" {} +

#for FILE in $(find $FINDPATH -type f)
#do
# #echo $FILE
# sed -i "s:$FINDPATH::" $FILE
#done



Đăng nhận xét