2009-05-25 66 views
53

我需要做一個正則表達式查找和替換文件夾(及其子文件夾)中的所有文件。 linux shell命令會做什麼?sed初學者:改變文件夾中的所有事件

例如,我想對所有文件運行此操作,並用新的替換文本覆蓋舊文件。

sed 's/old text/new text/g' 
+0

http://theunixshell.blogspot.com/2012/12/find-and-replace-string-in-all-files.html – Vijay 2013-05-13 07:20:16

回答

82

沒有辦法,只用sed的做到這一點。你需要使用至少find工具一起:

find . -type f -exec sed -i.bak "s/foo/bar/g" {} \; 

此命令將創建一個.bak文件的每個改變的文件。

注:

  • -i論據sed命令是GNU擴展,因此,如果您正在使用的BSD的sed這個命令你將需要輸出重定向到一個新的文件,然後重命名它。
  • find實用程序在舊的UNIX框中未實現-exec參數,因此,您需要改爲使用| xargs
0

我可以建議(在備份文件):

find /the/folder -type f -exec sed -ibak 's/old/new/g' {} ';' 
5

爲了便於攜帶,我不依賴於特定於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可以讀取它。

20

我更喜歡使用find | xargs cmd而不是find -exec,因爲它更容易記住。

這個例子在全球取代「富」與.txt文件「欄」等於或低於當前目錄:

find . -type f -name "*.txt" -print0 | xargs -0 sed -i "s/foo/bar/g" 

-print0-0選項可以被排除在外,如果你的文件名不包含時髦人物如空間。

+1

如果你在OSX,嘗試`找到。 -type f -name「* .txt」-print0 | xargs -0 sed -i''「s/foo/bar/g」`(注意爲`-i`參數提供一個空字符串)。 – jkukul 2017-03-27 09:10:58

-4

如果文件夾中的文件的名稱有一些常規名稱(如file1,file2 ...),我已用於循環。

for i in {1..10000..100}; do sed 'old\new\g' 'file'$i.xml > 'cfile'$i.xml; done 
+0

這與問題無關。這個問題沒有提到任何關於相同的文件/文件夾名稱模式。請避免這樣的答案 – 2017-10-16 10:12:52

相關問題