Quantcast
Channel: CodeSection,代码区,Linux操作系统:Ubuntu_Centos_Debian - CodeSec
Viewing all articles
Browse latest Browse all 11063

Replace in files recursively with sed

$
0
0

Replacing text in many files is reasonably simple with sed, on the command line.

If you do this, I would recommend that you come up with a way to take a backup, because there is almost no chance you’ll get it right on the first try.

My preferred approach is to make an empty git repository with the initial state, which allows me to rollback the changes every time I need to iterate on the sed script.

git init . git add -A git commit -m "files"

For this example, I’m adding an Amazon link to a bunch of files. The successful solution is as follows (you want the generate format of “s/ / /” to control it in your own script).

find . -type f -iname '*.html' -exec sed -i 's/"sidebar-module">/"sidebar-module"><iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="\/\/ws-na.amazon-adsystem.com\/widgets\/q?ServiceVersion=20070822\&OneJS=1\&Operation=GetAdHtml\&MarketPlace=US\&source=ss\&ref=as_ss_li_til\&ad_type=product_link\&tracking_id=thesecrelifeo-20\&marketplace=amazon\&region=US\&placement=0981531687\&asins=0981531687\&linkId=0dc4250b21bf0e833004fd3e58765806\&show_border=true\&link_opens_in_new_window=true"><\/iframe>/' "{}" +;

Once you create this script, you should check it in.

...add script... git add replace.sh git commit -m "script"

I found there were several problems getting this to work. You need to escape & and \, and make sure to replace what you removed it’s often helpful to use a chunk of text that comes before or after the replacement.

When you make a mistake, you can just do

git reset --hard

As long as you’re committing the replacement script as you go.

If you like, you can get rid of the git repository once you’re done, by doing this:

rm -rf .git

~

Looking for a good software development book? The Phoenix Project is a novel(!) about a failing software project, which I found to be an interesting read.

Viewing all articles
Browse latest Browse all 11063

Trending Articles