Bash and Script help generating files with variable content

别等时光非礼了梦想. 提交于 2019-12-22 01:00:24

问题


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!


回答1:


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>


来源:https://stackoverflow.com/questions/8599070/bash-and-script-help-generating-files-with-variable-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!