Salsinats
Salsinats

Reputation: 13

Append bash script content to another file

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

Upvotes: 0

Views: 170

Answers (2)

Ivan
Ivan

Reputation: 7287

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

Upvotes: 1

fr4gm3nt
fr4gm3nt

Reputation: 24

If You want to use variable try

for f in $filenames; do

Upvotes: 0

Related Questions