Bash and Script help generating files with variabl

2019-04-17 04:31发布

Extending this question: How to Create several files from a list in a text file?

Summary:

cat file_full_of_files_names | tr ' \t' '\n\n' | while read filename; do
if test -f "$filename"; then
echo "Skipping \"$filename\", it already exists"
else
   cp -i initial_content "$filename"
fi
done

works great for what I want, but I'd like to extend it. The content below is what is found in 'initial_content'

<?xml version="1.0" encoding="UTF-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/com_aac_cachemate_demo_cachemate" /> </selector>

I'd like to change the

@drawable/"XYZ"

XYZ variable to the name of the file created using the content from

initial_content

but with the XYZ variable filled in with the filenames from

file_full_of_file_names

content.

Any script kiddies? Bashers? Thanks for any help!

标签: bash cat
1条回答
Lonely孤独者°
2楼-- · 2019-04-17 05:20

Using AWK instead of cp:

cat file_full_of_files_names | tr ' \t' '\n\n' | while read filename; do
if test -f "$filename"; then
echo "Skipping \"$filename\", it already exists"
else
   awk -F"/" -v OFS="/" -v name="$filename" '/@drawable/{sub(/.*/,name"\"",$2);print;next}1' < initial_content > "$filename"

fi
done

Test:

jaypal:~/Temp] cat file # Sample File
<?xml version="1.0" encoding="UTF-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/com_aac_cachemate_demo_cachemate" /> </selector>

[jaypal:~/Temp] echo $filename # Variable Initialization
name

[jaypal:~/Temp]  awk -F"/" -v OFS="/" -v name="$filename" '/@drawable/{sub(/.*/,name"\"",$2);print;next}1' file
<?xml version="1.0" encoding="UTF-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/name"/> </selector>
[jaypal:~/Temp] 


[jaypal:~/Temp] filename="jaypal" # Re-initializing variable

[jaypal:~/Temp]  awk -F"/" -v OFS="/" -v name="$filename" '/@drawable/{sub(/.*/,name"\"",$2);print;next}1' file
<?xml version="1.0" encoding="UTF-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/jaypal"/> </selector>
查看更多
登录 后发表回答