linux 批量替换文件内容
1. sed
grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'
?
例如:
?
对象:文件夹
grep -rl 'windows' ./path | xargs sed -i 's/windows/linux/g'
?
2. find对象:文件
find -name 'test' | xargs perl -pi -e 's|windows|linux|g'
?
?这里使用了perl语言,使用-e加上一段代码,从而批量地将当前目录及所有子目录下的file.log文件中的string1替换成了string2; string支持正则表达式?3. awkgrep -i "windows" -r ./path | awk -F : '{print $1}' | sort | uniq | xargs sed -i 's/windows/linux/g'?这里使用了shell命令,先查找出文件,再用awk分割(以:切分),再行替换!注意:?? grep可以使用正则,也可以使用\转义一些特殊字符,比如“等??sed -i 's/"localhost"/"10.2.2.2"/g' /home/my.conf?更多:sed replace word / string syntax
The syntax is as follows:
sed -i 's/old-word/new-word/g' *.txt
?
GNU sed command can edit files in place (makes backup if extension supplied) using the -i option. If you are using an old UNIX sed command version try the following syntax:
sed 's/old/new/g' input.txt > output.txt
?
You can use old sed syntax along with bash for loop:
#!/bin/bashOLD="xyz"NEW="abc"DPATH="/home/you/foo/*.txt"BPATH="/home/you/bakup/foo"TFILE="/tmp/out.tmp.$$"[ ! -d $BPATH ] && mkdir -p $BPATH || :for f in $DPATHdo if [ -f $f -a -r $f ]; then /bin/cp -f $f $BPATH sed "s/$OLD/$NEW/g" "$f" > $TFILE && mv $TFILE "$f" else echo "Error: Cannot read $f" fidone/bin/rm $TFILE
?
A Note About Bash Escape CharacterA non-quoted backslash \ is the Bash escape character. It preserves the literal value of the next character that follows, with the exception of newline. If a \newline pair appears, and the backslash itself is not quoted, the \newline is treated as a line continuation (that is, it is removed from the input stream and effectively ignored). This is useful when you would like to deal with UNIX paths. In this example, the sed command is used to replace UNIX path "/nfs/apache/logs/rawlogs/access.log" with "__DOMAIN_LOG_FILE__":
#!/bin/bash## Our path_r1="/nfs/apache/logs/rawlogs/access.log" ## Escape path for sed using bash find and replace _r1="${_r1//\//\\/}" # replace __DOMAIN_LOG_FILE__ in our sample.awstats.confsed -e "s/__DOMAIN_LOG_FILE__/${_r1}/" /nfs/conf/awstats/sample.awstats.conf > /nfs/apache/logs/awstats/awstats.conf # call awstats/usr/bin/awstats -c /nfs/apache/logs/awstats/awstats.conf
?
The $_r1 is escaped using bash find and replace parameter substitution syntax to replace each occurrence of / with \/.
?
perl -pie Syntax For Find and ReplaceThe syntax is as follows:
perl -pie 's/old-word/new-word/g' input.file > new.output.file
?
来源:http://www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/
?