I have the directories structure as below:


Each .txt file in the directories has a word that I want to replace with the directory name.


"name": "Engineering",

I am looking to replace the word Engineering with the directory name, e.g. for Folder1:

"name": "Folder1"

My intial attempt is as below:

for f in Folder*; do (cd $f; echo $f; sed -i -e "s/Engineering/Folder*/" file.txt); done

However, the sed command doesn't seem to see Folder* as Folder numbers.

  • Great, catch, Freddy! It worked now:) – user3780018 Apr 13 at 20:33
  • Those files don't happen to be JSON files? If so, using jq rather than sed may be preferable (if one know anything about the structure of those JSON files). – Kusalananda Apr 13 at 20:49

There's no need to cd into the directory. You can loop over the file paths and extract the folder name:

for file in Folder*/file.txt; do
  sed -i -e "s/Engineering/${file%%/*}/" "$file"

The parameter expansion ${file%%/*} removes the longest suffix /* and leaves the folder name.

| improve this answer | |
  • Freddy, many thanks for the support! – user3780018 Apr 13 at 20:46
  • Hi Freddy, I noticed that the ${file%%/*} sometimes work and sometimes it doesn't! – user3780018 Apr 14 at 15:26
  • Sometimes, I get empty folder name! – user3780018 Apr 14 at 15:33
  • What is the pattern for the file path when the folder name is empty? – Freddy Apr 14 at 15:37
  • I would say e.g. jk-z30-t50-k001-za*/file.txt intead of Folder*/file.txt! – user3780018 Apr 14 at 15:40

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.