Structure
│ afile.md
│ script.sh
│
└───somelongdirectoryname
bfile.md
script.sh
find . -type f -name "*.md" -print | while read file_name
do
basename=$file_name
echo "
title: \"$basename\"
" | sed -e "s/.md//g" | sed -e "s/.\///g" > "$basename.tmp"
cat "$file_name" >> "$basename.tmp"
mv "$basename.tmp" "$file_name"
done
afile.md and bfile.md are initially empty.
After running script:
sh script.sh
Result:
afile.md
title: "afile"
bfile.md (under a subdirectory somelongdirectoryname)
title: "somelongdirectorynambfile"
Expected result of bfile.md was:
title: "bfile"
Notice how in the bfile.md the subdirectory name in appended to the start (which is NOT expected) and for some reason the e in somelongdirectorynam is cut off as you can see in the output! (which is again weird to me.)
My objective is to fill the files in all subdirectories (and their subdirectories) recursively with some textual content with a bash script.
What am I doing wrong and how do I fix this script?
CodePudding user response:
You should replace sed -e "s/.\///g" with sed -e 's/".*\//"/'. But, your whole script can be reduced to a single find command:
find . -type f -name '*.md' -exec bash -c \
't=${1##*/}; printf "\ntitle: \"%s\"\n\n" "${t%.md}" > "$1"' _ {} \;
CodePudding user response:
You can try this:
#!/bin/bash
find . -type f -name '*.md' -print0 |
while IFS='' read -r -d '' filename
do
basename=${filename##*/}
basename=${basename%.*}
printf '\ntitle: "%s"\n' "$basename" |
cat - "$filename" > "$basename.tmp"
mv "$basename.tmp" "$filename"
done
