0

This is my bash script

#!/bin/bash

filenames="root/simulate/*.txt"
for f in "$filenames"; do
#append "#" to all .txt files
 sed -i -e 's/^/#/' $filenames
#append content of this bash script to all .txt files
 cat "$0" >> "$f"
done

But instead of appending its bash script content to all existing ".txt" files, it creates a new "*.txt" file in the directory and adds the content of the other ".txt" files into it, and then appends the bash script to that new file. Can anybody help? Thank you

1
  • 1
    Why are you running sed on $filenames every time through the loop, instead of $f? Commented Aug 25, 2020 at 14:50

2 Answers 2

1

That is because * not expanding inside "", try it like this:

#!/bin/bash
for f in root/simulate/*.txt; do
    #append "#" to all .txt files
    sed -i -e 's/^/#/' "$f"
    #append content of this bash script to all .txt files
    cat "$0" >> "$f"
done

And you don't need a loop here, just this sed command:

#!/bin/bash
sed -i 's/^/#/;$r'"$0" root/simulate/*.txt
Sign up to request clarification or add additional context in comments.

Comments

0

If You want to use variable try

for f in $filenames; do

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.