简体   繁体   English

在脚本中的多个文件上使用sed

[英]Using sed on multiple files in a script

I have a sed script to insert a line before a keyword "MYWORD" found in the file. 我有一个sed脚本,可以在文件中找到的关键字“ MYWORD”之前插入一行。 My script is the following: 我的脚本如下:

sed -e '/MYWORD/ i\MY NEW LINE TO BE INSERTED' <inputFilename >outputFilename

Since this will only occur on just one file how can I change my script to have this insert occur on every file in the directory? 由于这只会发生在一个文件上,我该如何更改脚本以使此插入发生在目录中的每个文件上?

As nosid said, you can use the -i option to edit a file in place. 正如nosid所说,您可以使用-i选项在适当位置编辑文件。 Read the man page in YOUR operating system to determine exactly how to use -i . 阅读您的操作系统中的手册页,以准确确定如何使用-i Then you can wrap sed in a little bit of shell script to identify and act on the file: 然后,您可以将sed包装在一些shell脚本中,以识别文件并对其进行操作:

for this in foo*.txt; do
  sed -i'' -e 'your-sed-script' "$this"
done

That said, I'm not sure your insert method will work, or at least work reliably. 就是说,我不确定您的插入方法是否会起作用,或者至少可靠地起作用。 I tested in FreeBSD and OS X, and it didn't work at all. 我在FreeBSD和OS X上进行了测试,但是根本没有用。 My normal strategy for inserting lines is to use awk, instead. 我插入行的正常策略是使用awk。 Thus (for example): 因此(例如):

for this in foo*.txt; do
  awk '/MYWORD/{print "Extra line of text goes here."} 1' "$this" > "$this.$$"
  mv "$this.$$" "$this"
done

The awk line here searches for /MYWORD/ (an extended regular expression, whereas sed defaults to basic regular expressions). 此处的awk行搜索/ MYWORD /(扩展的正则表达式,而sed默认为基本正则表达式)。 If it finds it, it first prints the "Extra" text. 如果找到它,它将首先打印“其他”文本。 Then, the "1" evaluates as a "true" that will also print the current line. 然后,“ 1”评估为“ true”,也将打印当前行。 The effect is to insert the "Extra" text on the line before MYWORD. 效果是在“ MYWORD”之前的行上插入“额外”文本。

Note that this isn't a good script. 请注意,这不是一个好的脚本。 It's wasteful, piping and renaming files that haven't been modified. 这是浪费,管道化和重命名未修改的文件。 You could improve it by choosing to "mv" the temp file depending on an exit value from awk, or you could use cmp to determine if the file had changed, then clean up leftover tempfiles, etc... But it gets the point across. 您可以通过根据awk的退出值选择“ mv”临时文件来进行改进,或者可以使用cmp确定文件是否已更改,然后清除剩余的临时文件,等等。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM