简体   繁体   中英

Running multiple find and sed in a bash file

I have the code below

find . -type f -exec sed -i  's#<![endif]>##g' {} +
find . -type f -exec sed -i  's#<script src="/js/vendor/modernizr-2.6.2.min.js?v=201425100529"></script>##g' {} +   
find . -type f -exec sed -i  's# <!--[if lt IE 9]>##g' {} +       

in a bash file.

If I run the lines directly in terminal it works, but If I run them together in a sh file I have an error:

find: missing argument to '-exec'

The reason the command execution succeeds but the script failed is,

when the script gets executed the find command searches for all files and directories in the current execution path ( as . is used in find ). Again this also includes the script itself. This creates the script to be overwritten/modified by the sed .

And so instead of keeping the script in the same directory when the file edits needs to be done, the script can be kept in some other directory and an absolute path can be give to the find command.

And it is also recommended to terminate commands with \\; to indicate the end of arguments.

Always use bash to execute scripts instead of sh which means bourne shell . Generally bash will be a symlink for sh but it will run in a compatibility mode which causes bash to loose modern functions.

#!/bin/bash

find /Absolute/path -type f -exec sed -i  's#<!\[endif\]>##g' '{}' \;
find /Absolute/path -type f -exec sed -i  's#<script src="/js/vendor/modernizr-2.6.2.min.js?v=201425100529"></script>##g' '{}' \;
find /Absolute/path -type f -exec sed -i  's# <!--\[if lt IE 9\]>##g' '{}' \; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM