Forem

Konnor Rogers
Konnor Rogers

Posted on

3

Inserting a string on the first line of every file with Vim

Alright here it goes, I needed to add a header to all files. There are roughly ~72 files and I didn't want to do it by hand. The header in question was for test files in Shoelace.

I stumbled across this StackOverflow link:

https://stackoverflow.com/questions/30541582/how-do-i-insert-the-same-line-into-multiple-files-using-vim

Which was 99% of what I wanted, but didnt show how to use "put" without using a register.

So here's the magic few commands that saved me a bunch of time.

:args ./**/*.test.ts
:argdo 1put! = 'import \"../../../dist/shoelace.js\"' | write | update
Enter fullscreen mode Exit fullscreen mode

The first line :args ./**/*.test.ts tells us what files we want to look at. The second line: :argdo 1put! = 'import \"../../../dist/shoelace.js\"' | write | update says: "On the first line, put this statement above whatever is already on the first line, save the file, then update it in Vim.

That's all I got, mostly saving this for future me who may need this!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
pbnj profile image
Peter Benjamin (they/them) •

Nice use of vim & :arg family.

This is also possible with GNU sed:

sed -i '1i import "../../../dist/shoelace.js"' ./**/*.test.ts
Enter fullscreen mode Exit fullscreen mode

Or with macOS/BSD-variant of sed:

sed -i'' '1i\
import "../../../dist/shoelace.js"
' ./**/*.test.ts
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay