我需要做一個正則表達式查找和替換文件夾(及其子文件夾)中的所有文件。 linux shell命令會做什麼?sed初學者:改變文件夾中的所有事件
例如,我想對所有文件運行此操作,並用新的替換文本覆蓋舊文件。
sed 's/old text/new text/g'
我需要做一個正則表達式查找和替換文件夾(及其子文件夾)中的所有文件。 linux shell命令會做什麼?sed初學者:改變文件夾中的所有事件
例如,我想對所有文件運行此操作,並用新的替換文本覆蓋舊文件。
sed 's/old text/new text/g'
沒有辦法,只用sed的做到這一點。你需要使用至少find工具一起:
find . -type f -exec sed -i.bak "s/foo/bar/g" {} \;
此命令將創建一個.bak
文件的每個改變的文件。
注:
-i
論據sed
命令是GNU擴展,因此,如果您正在使用的BSD的sed
這個命令你將需要輸出重定向到一個新的文件,然後重命名它。find
實用程序在舊的UNIX框中未實現-exec
參數,因此,您需要改爲使用| xargs
。我可以建議(在備份文件):
find /the/folder -type f -exec sed -ibak 's/old/new/g' {} ';'
可能要嘗試my mass search/replace Perl script。與鏈式公用程序解決方案相比具有一些優勢(如不需要處理多層次的shell元字符解釋)。
爲了便於攜帶,我不依賴於特定於linux或BSD的sed功能。相反,我使用Kernighan的overwrite
腳本和派克關於Unix編程環境的書。
的命令是那麼
find /the/folder -type f -exec overwrite '{}' sed 's/old/new/g' {} ';'
而且overwrite
腳本(這是我使用所有的地方)是
#!/bin/sh
# overwrite: copy standard input to output after EOF
# (final version)
# set -x
case $# in
0|1) echo 'Usage: overwrite file cmd [args]' 1>&2; exit 2
esac
file=$1; shift
new=/tmp/$$.new; old=/tmp/$$.old
trap 'rm -f $new; exit 1' 1 2 15 # clean up files
if "[email protected]" >$new # collect input
then
cp $file $old # save original file
trap 'trap "" 1 2 15; cp $old $file # ignore signals
rm -f $new $old; exit 1' 1 2 15 # during restore
cp $new $file
else
echo "overwrite: $1 failed, $file unchanged" 1>&2
exit 1
fi
rm -f $new $old
的想法是,它僅覆蓋如果命令成功的文件。有用的find
也,你不會想使用
sed 's/old/new/g' file > file # THIS CODE DOES NOT WORK
因爲shell截斷文件之前sed
可以讀取它。
我更喜歡使用find | xargs cmd
而不是find -exec
,因爲它更容易記住。
這個例子在全球取代「富」與.txt文件「欄」等於或低於當前目錄:
find . -type f -name "*.txt" -print0 | xargs -0 sed -i "s/foo/bar/g"
的-print0
和-0
選項可以被排除在外,如果你的文件名不包含時髦人物如空間。
如果你在OSX,嘗試`找到。 -type f -name「* .txt」-print0 | xargs -0 sed -i''「s/foo/bar/g」`(注意爲`-i`參數提供一個空字符串)。 – jkukul 2017-03-27 09:10:58
如果文件夾中的文件的名稱有一些常規名稱(如file1,file2 ...),我已用於循環。
for i in {1..10000..100}; do sed 'old\new\g' 'file'$i.xml > 'cfile'$i.xml; done
這與問題無關。這個問題沒有提到任何關於相同的文件/文件夾名稱模式。請避免這樣的答案 – 2017-10-16 10:12:52
http://theunixshell.blogspot.com/2012/12/find-and-replace-string-in-all-files.html – Vijay 2013-05-13 07:20:16