Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to append string to multiple files in same directory

Tags:

bash

append

Is there a way to write a BASH script that will append a string to every file in a directory?

e.g., I want to append the string "test" to every .html file in the current working directory I'm in; something like:

echo "test" >> *.html

But of course this doesn't work.

like image 770
James Nine Avatar asked Sep 09 '10 01:09

James Nine


People also ask

How do you append the contents of multiple files in Unix?

Type the cat command followed by the file or files you want to add to the end of an existing file. Then, type two output redirection symbols ( >> ) followed by the name of the existing file you want to add to.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do I append to a bash script?

To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.


3 Answers

Nevermind, I figured it out.

#!/bin/sh

for f in *.html ; do
    echo "test" >> $f
done
like image 153
James Nine Avatar answered Sep 20 '22 15:09

James Nine


tee is good for these sorts of things.

echo "test" | tee -a *.html
like image 27
Dean Rather Avatar answered Sep 18 '22 15:09

Dean Rather


sed -i.bak '$a append' *.html
like image 20
ghostdog74 Avatar answered Sep 19 '22 15:09

ghostdog74