0

I am looking for a simple command line script or shell script I can run that, with a given directory, will traverse all directories, sub directories and so on looking for files with .rb and indent them to two spaces, regardless of current indentation.

It should then look for html, erb and js files (as well as less/sass) and indent them to 4.

Is this something thats simple or am I just over engineering it? I dont know bash that well, I have tried to create something before but my friend said to use grep and I am lost. any help?

1 Answer 1

2

If you've got GNU sed with the -i option to overwrite the files (with backups for safety), then:

find . -name '*.rb' -exec sed -i .bak  's/^/  /' {} +

find . -name '*.html' -exec sed -i .bak 's/^/    /' {} +

Etc.

The find generates the list of file names; it executes the sed command, backs up the files (-i .bak) and does the appropriate substitutions as requested. The + means 'do as many files at one time as is convenient. This avoids problems with spaces in file names, amongst other issues.

Sign up to request clarification or add additional context in comments.

4 Comments

The question states "regardless of current indentation", so I believe you want s/^[ ^I]*/ / (where ^I is a literal tab).
@WilliamPursell: Oh, you mean people still use tabs? How quaint! Yes; if you have tabs at the start of a line, you want the spaces after the tabs. But your modified regex would need to be s/^[ ^I]*/& / as otherwise you're undoing all existing indentation and replacing it with two spaces.
I interpret the question to mean the new indentation should discard the old indentation, so & is not desired. Your original regex is far more appropriate than adding & if your interpretation is correct.
Hmmm...the question does say 'indent them to two spaces' where I interpreted it to mean 'by two spaces'. OK; I accept your rewrite of the regex as probably being correct (though neither makes an awful lot of sense as an operation; I'd not do it to my source code, that's for sure!). I think the key part of the question was 'how to apply a systematic edit to a bunch of files', and the framework provided is still correct — even if the regexes need adjustment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.