How do I change the content of multiple files to match their directory name?
I have multiple directories 9.[0-9]15
with a file file1
that has content like:
#/9.015/file1
blah
9.015 blah
blah 9.01577 blah
blah
I copied this one file1
to all directories. I would like to change this file from each directory to match the name of the directory they are in. Thus /9.115/file1
:
#/9.115/file1
blah
9.115 blah
blah 9.11577 blah
blah
Etc. I know I need to use a regex bunch to find and change the part I would like, but I don't know how to loop through this file from each directory using the directory name as a replacement in the file.
source to share
Try the following:
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 am using echo
and sed
to get the required part of the filename.
As @ 4ae1e1, referred to in the comments below, you can use the advanced settings in place echo
+ sed
: d=${i%/*}
. For more information on parameter expansion, see the documentation .
As for me, the extension syntax is pretty hard to remember :( And IMHO for ad hoc, shot one liner once to do some "unnecessary" forks.
And yes, it's a good idea to use readable variable names.
source to share