0

I have a file which has the number of .pdfs in my folder. I assign this number to a variable, fileNum like so:

fileNum=$(ls -l *.pdf | wc -l)

echo $fileNum returns this number without any problem. Now I need to use fileNum in a for loop and I am having problems with it.

My for loop is:

for i in {1..$fileNum}
do
 var=$(awk 'NR=='$i 'pdfs.file')

 gs \
 -sOutputFile="exgs_"$var \
 -sDEVICE=pdfwrite \
 -sColorConversionStrategy=Gray \
 -dProcessColorModel=/DeviceGray \
 -dCompatibilityLevel=1.4 \
 -dNOPAUSE \
 -dBATCH \
$var

done

The $ at the beginning of fileNum gives me an error message which is:

awk: line 1: syntax error at or near {

Things are fine when I actually use the number itself (which in this case is 17). Obviously, awk doesn't like this because of ... something.... I don't know what. What should I do about this?

I tried other forms such as $(fileNum) and filenum with the single quotes around it. Is it something to do with strings?

1
  • first step: debugging: echo 'NR=='$i Commented Aug 20, 2012 at 16:13

3 Answers 3

4

I'd use bash to read the file instead of running awk for every line.

while read -r file; do
    gs -sOutputFile="exgs_$file" \
       -sDEVICE=pdfwrite \
       -sColorConversionStrategy=Gray \
       -dProcessColorModel=/DeviceGray \
       -dCompatibilityLevel=1.4 \
       -dNOPAUSE \
       -dBATCH \
       "$file"
done < pdfs.file

See also http://mywiki.wooledge.org/BashFAQ/001

Otherwise, for the general case where you want to iterate from 1 to n, I'd use a C-style for-loop.

n=10
for (( i=1; i <= n; i++)); do
   ...
done
Sign up to request clarification or add additional context in comments.

Comments

2

This is because Bash will do the expansion on the braces before the variable. You need to use eval in this case so that Bash expands the variable first.

for i in $(eval echo {1..$fileNum})
do
 var=$(awk 'NR=='$i 'pdfs.file')

 gs \
 -sOutputFile="exgs_"$var \
 -sDEVICE=pdfwrite \
 -sColorConversionStrategy=Gray \
 -dProcessColorModel=/DeviceGray \
 -dCompatibilityLevel=1.4 \
 -dNOPAUSE \
 -dBATCH \
$var

done

2 Comments

And here is a thread on linuxquestions.org that talks about it too. linuxquestions.org/questions/programming-9/…
0

I would rather write:

for i in $(seq $fileNum)
do
  ....
done

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.