Home > Mobile >  Copy files based on content
Copy files based on content

Time:09-08

Need to find all files in specific subdirectories ending in .xml. They'll either be in .../etc/apps//local/data/ui/views/.xml or .../etc/apps//default/data/ui/views/.xml. If the file in /etc/apps//default/data/ui/views/*.xml doesn't have the string 'version="1.1"' in the first line, copy the file to the local directory as the same file name, add that string to the first line and quit. I'm stuck on copying the file from it's default dir to it's local dir. I've got:

src=.../etc/apps/*/default/data/ui/views/*.xml
dest=.../etc/apps/*/local/data/ui/views/
pat='version='
for file in $src
do
        if [[ "$(sed -n '1{/version=/p};q' "$file")" ]]; then
                awk 'NR==1 {print; exit}' "$file"
                echo "No change necessary to $file"
        else
                echo "Copying $file to local ../local/data/ui/views/$file and running sed '1 s/>/ version="1.1">/'"
        fi
done

Which won't work because it's going to use the whole path for $file like I told it to. I get the feeling I'm overthinking this. But I'm not sure where to go from here.

CodePudding user response:

You might want to use pipes and basename. E.g.

ls <DIR>/*.xml | while read FULLPATH; do 
   SRC=$(basename $FULLPATH)
   <your code>
done

CodePudding user response:

Here is one solution/approach with bash and find and ed to edit the file in place, but change to something available in your system.

#!/usr/bin/env bash

str='version="1.1"'
src=../etc/apps/default/data/ui/views
dest=../etc/apps/local/data/ui/views

while IFS= read -rd '' -u3 files; do
  IFS= read -r first_line < "$files"
  if [[ $first_line = *"$str"* ]]; then
    printf 'No change necessary to %s\n' "$files"
  else
    printf "Copying %s to local %s\n" "$files" "$src/${files##*/}"        
    cp -v "$files" "$dest" || exit
    printf 'Inserting %s at the first line of %s\n' "$str" "$dest/${files##*/}"
    printf '%s\n' '0a' "<?xml ${str}?>" . w q | ed -s "$dest/${files##*/}"
  fi
done 3< <(find "$src" -type f -name '*.xml' -print0)
  • Related