简体   繁体   English

如何根据目录名更改多个文件的内容?

[英]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. 在这里,我使用echosed来获取文件名的必要部分。

As @4ae1e1 mentioned in comments below, you can use parameter expansion instead of echo + sed : d=${i%/*} . 正如下面评论中提到的@ 4ae1e1,您可以使用参数展开而不是echo + sedd=${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.

相关问题 如何读取文件的内容,然后将内容拆分为多个文件? - How to read content of a file and then split the content into several files? 如何在目录中匹配此文件名模式,并输出匹配的文件? - How can I match this pattern of file name in a directory, and output the matched? 如何使用find和awk更改文件内容? - How can I change file content with find and awk? 根据目录名称对正则表达式输出进行分组 - Grouping Regex Output According to Directory Name 如何正确更改字典中的键名? - How can i properly change the keys name in my dict? 使用元数据内容重命名几个文件 - Rename several files using its metadata content 如何使用文件动态指定模式并根据该目录中的模式获取文件? - How to specify pattern dynamically using file and get files according to pattern from that directory? 如何使用perl regex删除字符串的第一个目录名称(顶级) - How can I use perl regex to remove the first directory name (top level) of a string 如何在文件名中查找带有完整日期的文件并将其与类似文件进行比较? - How can I find files with a full date in the file name and compare them to similar files? 如何使用文件名创建新目录并将关联文件移动到新目录中? - How can I make new directories using file names and move associated files into that new directory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM