I have thousands of directories, all of them has this format;


and i have a file called x.txt, it's content should have

[USERNAME] and some static text...

so when i do dir /var/www/vhosts/*/conf/ , I am getting all the directories that I need to copy the file under, however, I don't know how to grab that [USERNAME] and put it in that file that i need to copy.

All suggestions welcome. I can only use shell scripting on this environment.


cd /var/www/vhosts && for d in */; do
   echo "$user blah blah" > "${d}/conf/x.txt"

... should get you pretty much what you want.


Dennis and Mike make sure you're quoting ${dir}. If there are any directories with spaces this could result in some issues.

echo "$user and some static text..." > "${dir}/conf/x.txt"

For portability's sake I would use "${d%%.*}" for finding the user's name.

  • good point on the quotes, and your tip on ${d%%.*} saves over 1000 calls to awk, updated! – Mike Pountney Jan 24 '10 at 12:26

Here's another way to do it:

cd /var/www/vhosts &&
find -maxdepth 1 -mindepth 1 -type d -print0 |
while read -d '' -r dir
    user=$(basename "$dir" .company.com)
    echo "$user and some static text..." > "${dir}/conf/x.txt"
  • Thanks Dennis, I wish I could choose two answers. Would you recommend any good book/url on the subject? – Devrim Jan 24 '10 at 18:51
  • On Bash scripting? Search ServerFault and StackOverflow. There are questions/answers that'll point the way. One I can recommend is mywiki.wooledge.org/EnglishFrontPage – Dennis Williamson Jan 24 '10 at 20:50
  • Thanks Dennis. It's always good to learn from a pro what is worth reading. – Devrim Jan 25 '10 at 1:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.