简体   繁体   中英

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.015/file1
blah
9.015 blah
blah 9.01577 blah
blah

I've copied this file1 to all directories. 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
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.

As @4ae1e1 mentioned in comments below, you can use parameter expansion instead of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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