0

I have the directories structure as below:

Folder1/ |____file.txt Folder2/ |____file.txt Folder3/ |____file.txt : Foldern/ |____file.txt 

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

file.txt:

"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.

2
  • Great, catch, Freddy! It worked now:)CommentedApr 13, 2020 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
    CommentedApr 13, 2020 at 20:49

1 Answer 1

2

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" done 

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

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.