Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save WhiteMinds/27cae6d87590649d90509c2659fb787a to your computer and use it in GitHub Desktop.
Save WhiteMinds/27cae6d87590649d90509c2659fb787a to your computer and use it in GitHub Desktop.
Bash Script: Refactor resources used by a single component into the component's own folder to make it more cohesive

in WSL Ubuntu

asset_dir="./src/assets" 
code_dir="./src"

find "$asset_dir" -name "*.svg" -o -name "*.png" -o -name "*.gif" | 
  sed 's@'"$asset_dir"'/@@g' |
  xargs -I{} sh -c '
    asset_dir="./src/assets" 
    filename={}
    match_count=$(grep -rl "$filename" '$code_dir' | wc -l)
    if [ $match_count -eq 1 ]; then
      match_file=$(grep -rl "$filename" '$code_dir')
      match_dir=$(dirname "$match_file")
      echo "$asset_dir"/"$filename" to "$match_dir"
      mv "$asset_dir"/"$filename" "$match_dir"
      sed -i "s|from ['\''\"]\(\(\.\./\)\+assets/\)\?$filename['\''\"]|from '\''./$filename'\''|" "$match_file"
      sed -i "s|url(['\''\"]\(../\)*assets/$filename['\''\"])|url\('\''./$filename'\''\)|" "$match_file"
    fi
  '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment