Ok. I will correct your script and will suggest alternatives. A working version can be:
Code:
#!/bin/bash
if [ -z $1 ]; then
echo "Needs directory as argument."
exit 1
elif [ -d "$1" ]; then
dirname="$1"
fi
cd $1
list="$(ls ARCH*.dat)"
echo $list
for i in $list
do
sed -i '$a input text' $i
done
To test if $1 is a directory, use the -d test, not -f. The former checks if the name is a directory, the latter checks if the name is a regular file.
Moreover, when you embed $list in double quotes, the list of files is interpreted as a single string with file names separated by space (this is a side effect of the shell expansion). Hence the for loop is executed only once and the resulting sed command is something like:
Code:
sed '$a input text' ARCH1.dat ARCH2.dat ARCH3.dat ARCH4.dat ...
for this reason you append a string to the content of the last file only. Removing the double quotes gives the result you expect. You can also use the command substitution directly in the for loop, avoiding the assignment to the variable list:
Code:
for i in $(ls ARCH*.dat)
do
sed -i '$a input text' $i
done
In addition, to actually modify the content of the file you have to use the -i option of sed.
The sed command is ok, since it appends (a) the string (input text) to the end ($) of the file. Indeed the special character $ in a sed command matches the last line in the file. However this works only if the file is not empty, that is if there is at least one line in the file.
To keep it simple you can use echo instead of sed
Code:
echo input text >> $i
This will echo the string and append it to the file. The double redirection (>>) means append.
Finally I suggest some good reading about shell scripting and sed (and also awk for future reference).
Bash Guide for beginners
Advanced Bash-Scripting Guide
Sed - An Introduction and Tutorial
Gawk: Effective AWK Programing
Have a nice scripting time!
