Case-insensitive search and replace with sed

前端 未结 8 1910
暗喜
暗喜 2020-11-28 08:51

I\'m trying to use SED to extract text from a log file. I can do a search-and-replace without too much trouble:

sed \'s/foo/bar/\' mylog.txt
<
8条回答
  •  暖寄归人
    2020-11-28 09:28

    I had a similar need, and came up with this:

    this command to simply find all the files:

    grep -i -l -r foo ./* 
    

    this one to exclude this_shell.sh (in case you put the command in a script called this_shell.sh), tee the output to the console to see what happened, and then use sed on each file name found to replace the text foo with bar:

    grep -i -l -r --exclude "this_shell.sh" foo ./* | tee  /dev/fd/2 | while read -r x; do sed -b -i 's/foo/bar/gi' "$x"; done 
    

    I chose this method, as I didn't like having all the timestamps changed for files not modified. feeding the grep result allows only the files with target text to be looked at (thus likely may improve performance / speed as well)

    be sure to backup your files & test before using. May not work in some environments for files with embedded spaces. (?)

提交回复
热议问题