Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenharman/b88d74e7e8eb51b84c85629b66cb91fd to your computer and use it in GitHub Desktop.
Save stevenharman/b88d74e7e8eb51b84c85629b66cb91fd to your computer and use it in GitHub Desktop.
Add a line of text to a file ONLY if the file doesn't already contain the line. Oh, but first append a line to the start of every file without that line. grep, sed, and xargs, folks!
# So… uuuh… what had happend was - I'd changed our `.rspec` config so that we
# could have isolated specs. The only real change was to not auto-require
# `rails_helper` in the `.rspec` config. Instead we auto-require `spec_helper`,
# and then files that need `rails_helper` (to boot rails) will have to add
# `require 'rails_helper'`.
#
# I didn’t think much of it b/c I’d noted that the specs I’d been looking at
# were already doing `require 'rails_helper'`, so it should be a no-op for
# them. It turns out, 700 or so other spec files ARE NOT already requiring
# `rails_helper`. So… what does one do when confronted with needing to in-place
# edit hundreds of files, but only if they don’t already have the line you want
# to add? Reach for `grep`, `sed`, and `xargs`, of course! Behold this
# monstrosity!
# First, find all _spec.rb files missing the "# frozen_string_literal: true"
# comment and add it as the first line.
grep --files-without-match --fixed-strings "# frozen_string_literal: true" ./spec/**/*_spec.rb | \
xargs sed -i '' -e "1s/^/# frozen_string_literal: true\n\n/"
# Now that all spec files have the comment, key on it for a line to replace.
# The find all _spec.rb files missing "require 'rails_helper'" and add it, via
# the comment from above
grep --files-without-match --fixed-strings "require 'rails_helper'" ./spec/**/*_spec.rb | \
xargs sed -i '' -e "s/# frozen_string_literal: true/# frozen_string_literal: true\n\nrequire 'rails_helper'/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment