在 bash 脚本中运行 vi 并执行 vi 命令来编辑另一个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22014830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:41:37  来源:igfitidea点击:

Running vi within a bash script and executing vi commands to edit another file

bashshellterminaleditorvi

提问by user3144035

So I've made a script which is collecting data from many different files:

所以我制作了一个脚本,它从许多不同的文件中收集数据:

#!/bin/bash

mkdir DATAPOOL""

grep achi *out>runner
grep treat *out>>runner

cat runner | grep Primitive *gout | grep '=   '|awk '{print ,}' > CellVolume"".txt 
cat runner | grep ' c ' *gout | grep 'Angstrom   '|awk '{print ,}' > Cellc"".txt 
cat runner | grep 'Final energy ' *gout |awk '{print ,}' > CellEnergy"".txt

etc etc

等等等等

cat runner |awk '{print "~/xtlanal",," > ",}' >runner2
vi runner2
:1,$s/gout:/xtl/
:1,$s/gout:/dat/
:wq

source runner2

grep Summary *dat | grep 'CAT-O  ' |awk '{print ,}' > AVE_NaO_"".txt

mv *txt DATAPOOL""

So I end up with all the required text files when run without the vi part and so I know it all works. Furthermore when I run it with the vi commands, it just stops running at the vi command and then i can manually enter the 3 commands and I end up with the correct results. What I'm struggling with is I cant get vi to run the commands on its own so I can just execute the file multiple times within different directories and not have to manually enter commands time and time again.

所以在没有 vi 部分的情况下运行时,我最终得到了所有必需的文本文件,所以我知道一切正常。此外,当我使用 vi 命令运行它时,它只会在 vi 命令处停止运行,然后我可以手动输入 3 个命令,最终得到正确的结果。我正在努力解决的是我无法让 vi 自己运行命令,所以我只能在不同的目录中多次执行文件,而不必一次又一次地手动输入命令。

Any help would be greatly appreciated.

任何帮助将不胜感激。

Cheers

干杯

回答by glenn Hymanman

For scripted editing tasks, you can use edinstead of vi:

对于脚本化编辑任务,您可以使用ed代替 vi:

ed runner2 <<'END'
1,$s/gout:/xtl/
1,$s/gout:/dat/
w
q
END

For global line-oriented search and replace, sedis a good choice:

对于全局面向行的搜索和替换,sed是一个不错的选择:

sed -i 's/gout:/xtl/; s/gout:/dat/' runner2

回答by B.Kocis

something like this as a bash script:

像这样的 bash 脚本:

#!/bin/bash
vi filename.txt -c ':g/^/m0' -c ':wq'

where -c execute a command. Here the command is to reverse the lines in a textfile. After done, :wq to save and exit. (man vi to get more about -c)

其中 -c 执行命令。这里的命令是反转文本文件中的行。完成后, :wq 保存并退出。(man vi 获得更多关于 -c 的信息)