[英]How can I change content of several files according to their directory name?
I have several directories 9.[0-9]15
with a file file1
which has content like: 我有几个目录
9.[0-9]15
,文件file1
内容如下:
#/9.015/file1
blah
9.015 blah
blah 9.01577 blah
blah
I've copied this file1
to all directories. 我已将此
file1
复制到所有目录。 I'd like to modify this file from every directory according to the name of the directory they are in. So that /9.115/file1
is: 我想根据它们所在目录的名称从每个目录修改这个文件。所以
/9.115/file1
是:
#/9.115/file1
blah
9.115 blah
blah 9.11577 blah
blah
And so on. 等等。 I know I have to use a regex group to find and modify the part I'd like, but I don't know how to cycle trough that file of every directory while using the directory name as the replacement on the file.
我知道我必须使用正则表达式组来查找和修改我喜欢的部分,但我不知道如何在使用目录名作为文件的替换时循环通过每个目录的文件。
Try this: 尝试这个:
for i in 9.[0-9]15/file1 ; do d=`echo $i|sed 's/^\(9\.[0-9]15\).*/\1/'` ; sed -i $i -e "s/9.015/$d/" ; done
Here I use echo
and sed
to get the necessary part of filename. 在这里,我使用
echo
和sed
来获取文件名的必要部分。
As @4ae1e1 mentioned in comments below, you can use parameter expansion instead of echo
+ sed
: d=${i%/*}
. 正如下面评论中提到的@ 4ae1e1,您可以使用参数展开而不是
echo
+ sed
: d=${i%/*}
。 More on parameter expansion see in documentation . 更多参数扩展看到的文档 。
As for me, the syntax of expansions is quite hard to remember :( And IMHO for ad hoc one shot one-liner it's OK to make some "unnecessary" forks. 至于我,扩展的语法很难记住:(和恕我直言, 特别是一次性单行,可以制作一些“不必要的”分叉。
And yes, it's a good idea to use readable variable names. 是的,使用可读变量名称是个好主意。
这就是我这样做的原因,感谢我在这里收到的帮助。
$ for dir in $(echo *); do cd $dir; sed -i "s/9.015/$dir/g" file1; cd ..; done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.