简体   繁体   中英

Bash script to rename folder with dynamic name and replace it's strings inside

I'm just starting to use Docker, and I'm newbie in bash scripts, but now I need to write bash script that will do next thing:

  1. I have 2 dirs with some subdirs: Rtp/ and Rtp-[version]/ , I need if Rtp-[version]/ dir exists rename it to the Rtp/ and override it's content. [version] - is dynamic number.

My dir structure:

|-- Rtp
     |--- subdir 1
     |--- subdir 2
|-- Rtp-1.0 (or Rtp-1.6, Rtp-2.7)
     |--- subdir 1
     |--- subdir 2
  1. After this I need in the new Rtp/ dir find specific file app.properties , and change inside of it string: myvar=my value to string myvar=new value , and do the same thing with 3 more files

I tried this link: http://stackoverflow.com/questions/15290186/ …: find . -name 'Rtp-' -exec bash -c 'mv $0 ${0/*/Rtp}' {} \\; find . -name 'Rtp-' -exec bash -c 'mv $0 ${0/*/Rtp}' {} \\; The problem that if dir already exists it move one directory into another.

Also I want rename it and not copy because it's big dir, and it can take some time to copy.

Thanks in advance, can you explain please the solution, in order to I will can change in the future if something will be changed.

1.

for dir in $(find Rtp-[version] -maxdepth 1 -type d): do cp -Rf $dir Rtp done

  • Find all directories in Rtp-version
  • Iterate through all of the results ( for... )
  • Copy recursively to Rtp/, and -f will overwrite

2.

for f in $(find Rtp -type f -name "app.properties"): do sed -ie s/myvar=myval/myvar=newval/ $f done

  • Find all files named app.properties
  • Use sed (the Stream editor) to -i interactively -e search for a string (by regex) and replace it (eg s/<oldval>/<newval>/ ). Note that oldval and newval will need to be escaped. If they contain a lot of / 's,you could do something like s|<oldval>|<newval>| .

Based on @Brian Hazeltine answer and Check if a file exists with wildcard in shell script

I found next solution:

if ls Rtp-*/ 1> /dev/null 2>&1; then
  mv -T Rtp-*/ Rtp
  find appl.properties -type f -exec sed -ie 's/myvar=my value/myvar=new value/' {} \;
fi

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