bat文件交互式命令
While a multitude of methods exist to search for and replace words in a single file, what do you do when you’ve got a string to update across multiple unrelated files, all with different names? You harness the power of command-line tools, of course!
尽管存在多种方法来搜索和替换单个文件中的单词,但是当您要在多个不相关的文件中使用一个字符串来更新它们时,您会怎么办呢? 当然,您可以利用命令行工具的强大功能!
First, you’ll need to find
all the files you want to change. Stringing together what are effectively search queries for find
is really only limited by your imagination. Here’s a simple example that finds Python files:
首先,您需要find
所有要更改的文件。 串在一起什么有效的搜索查询, find
是真的只限于你的想象力。 这是一个查找Python文件的简单示例:
find . -name '*.py'
The -name
test searches for a pattern, such as all files ending in .py
, but find
can do a lot more with other test conditions, including -regex
tests. Run find --help
to see the multitude of options.
-name
测试搜索模式,例如所有以.py
结尾的文件,但是find
可以在其他测试条件(包括-regex
测试)下做更多的事情。 运行find --help
以查看众多选项。
Further tune your search by using grep
to get only the files that contain the string you want to change, such as by adding:
通过使用grep
进一步调整搜索,以仅获取包含要更改的字符串的文件,例如添加:
grep -le '\<a whale\>'
The -l
option gives you just the file names for all files containing a pattern (denoted with -e
) that match “a whale.”
-l
选项仅提供包含与“鲸鱼”匹配的模式(以-e
表示)的所有文件的文件名。
Using Vim’s impressive :bufdo
lets you run the same command across multiple buffers, interactively working with all of these files without the tedium of opening, saving, and closing each file, one at a time.
使用Vim令人印象深刻的:bufdo
,您可以跨多个缓冲区运行相同的命令,以交互方式处理所有这些文件,而不必一次打开,保存和关闭每个文件。
Let’s plug your powerful find
+grep
results into Vim with:
让我们使用以下命令将功能强大的find
+ grep
结果插入Vim:
vim `find . -name '*.py' \
-exec grep -le '\<a whale\>' {} \;`
Using backtick-expansion to pass our search to Vim opens up multiple buffers ready to go (do :h backtick-expansion
in Vim for more). Now you can apply the Vim command :bufdo
to all of these files and perform actions such as interactive search-and-replace:
使用backtick-expansion将我们的搜索传递给Vim将打开准备使用的多个缓冲区(在Vim中执行:h backtick-expansion
可获得更多信息)。 现在,您可以将Vim命令:bufdo
应用于所有这些文件,并执行诸如交互式搜索和替换之类的操作:
:bufdo %s/a whale/a bowl of petunias/gce
The g
for “global” will change occurrences of the pattern on all lines. The e
will omit errors if the pattern is not found. The c
option makes this interactive. If you’re feeling confident, you can omit it to make the changes without reviewing each one.
“全局”的g
会更改所有行上模式的出现。 如果找不到该模式,则e
将忽略错误。 c
选项使此交互。 如果您有信心,则可以忽略它以进行更改,而无需查看每个更改。
When you’ve finished going through all the buffers, save all the work you’ve completed with:
完成所有缓冲区的操作后,请保存完成的所有工作:
:bufdo wq!
Then bask in the glory of your saved time and effort.
然后享受节省的时间和精力的荣耀。
bat文件交互式命令