My own rendition of your script would probably look like:
set -- *.java
test -e "$1" && {
fortyequals=$(printf '%040d\n' | tr 0 \=)
for javaFile do
printf '%s\nIn file: %s\n%s\n' \
$fortyequals "$javaFile" $fortyequals
grep -E '^[^/]{2}.*(ftp|http)' "$javaFile"
done
} >>~/Desktop/externalservers.txt
The solution already offered is needlessly shell-specific. You could achieve the same effect with portable syntax - which makes for less to remember in the long run with the added advantage of being more robust like:
set -- *.java
test -e "$1" &&
for javaFile do
# ...iterate on $javaFile here...
done
Another advantage is that you not only retain the most recent value of $javaFile
following the loop, you also retain all of the values that $javaFile
ever had in $@
. This makes the following possible:
...
done
echo "The previous for loop processed $# files."
echo "The first file processed was:"
printf "///\t'%s'\t///\n" "$1"
echo "The last file processed was:"
printf "///\t'%s'\t///\n" "$javaFile"
echo 'All files processed in the for loop were:'
printf "///\t'%s'\t///\n" "$@"
And if you do really like the {
curlies }
you can use them - even in bash
(though they are unnecessary) - but you have to delimit between the two shell reserved words }
and done
like:
for ... do {
...
} ; done
Though my recommendation is that you enclose the entire block - around the for
loop and any post processing you do - in curlies dependent on the &&
reserved words like:
set -- *.java
test -e "$1" && {
for ... done
# ...further processing on $@...
}
Looking back at it and I believe I can help a great deal with the regex as well... It looks like we're looking for lines containing the words http and/or ftp that do not begin with two //.
I think the rest is a result of the separate grep
operations you do. You appear to be attempting to clear blank lines, but, as I imagine, those are only caused in the first place by repeated appended writes to the file.
So, instead, we could just write for
loop's output directly to the outfile in order to maintain the write descriptor for ~/Desktop/externalservers.txt
until the loop has finished, which should avoid any blank lines being written. Maybe like:
for ... done >>outfile
Or
{ grouped ; command ; list ; } >>outfile
At the very least I can tell you that this statement probably does not do what you want:
sed 's/^\n//' $file
sed
is \n
ewline delimited - it's impossible to encounter a \n
ewline as the ^
first character on a line. You can get \n
ewlines into sed
's pattern space by various means, but never without some processing.
ls ..
you have there. Let the shell expand the arguments for you as Joseph's answer shows.