0

I am using sh shell script to read the files of a folder and display on the screen:

for d in `ls -1 $IMAGE_DIR | egrep "jpg$"`
do
  pgm_file=$IMAGE_DIR/`echo $d | sed 's/jpg$/pgm/'`

  echo "file  $pgm_file";
done

the output result is reading line by line:

file file1.jpg

file file2.jpg

file file3.jpg

file file4.jpg

Because I am not familiar with this language, I would like to have the result that print first 2 results in the same row like this:

file file1.jpg; file file2.jpg;

file file3.jpg; file file4.jpg;

In other languages, I just put d++ but it does not work with this case.

Would this be doable? I will be happy if you would provide me sample code.

thanks in advance.

1
  • Note : echo has a '-n' option for not adding an end-of-line. Commented Dec 14, 2011 at 15:31

4 Answers 4

3

Let the shell do more work for you:

end_of_line=""
for d in "$IMAGE_DIR"/*.jpg
do
  file=$( basename "$d" )
  printf "file %s; %s" "$file" "$end_of_line"
  if [[ -z "$end_of_line" ]]; then
    end_of_line=$'\n'
  else
    end_of_line=""
  fi

  pgm_file=${d%.jpg}.pgm
  # do something with "$pgm_file"
done
Sign up to request clarification or add additional context in comments.

Comments

1
for d in "$IMAGE_DIR"/*jpg; do
  pgm_file=${d%jpg}pgm
  printf '%s;\n' "$d"
done |
  awk 'END { 
        if (ORS != RS)
          print RS
          }
       ORS = NR % n ? FS : RS
       ' n=2

Set n to whatever value you need. If you're on Solaris, use nawk or /usr/xpg4/bin/awk (do not use /usr/bin/awk).

Note also that I'm trying to use a standard shell syntax, given your question is sh related (i.e. you didn't mention bash or ksh, for example).

Comments

0

Something like this inside the loop:

echo -n "something; "
[[ -n "$oddeven" ]] && oddeven= || { echo;oddeven=x;}

should do.

Three per line would be something like

[[ "$((n++%3))" = 0 ]] && echo

(with n=1) before entering the loop.

2 Comments

Hi, I dont get it, what if I add 3 files in a line?
That would be different, this one just toggles linefeed. I'll add the snippet for you...
0

Why use a loop at all? How about:

ls $IMAGE_DIR | egrep 'jpg$' |
   sed -e 's/$/;/' -e 's/^/file /' -e 's/jpg$/pgm/' |
   perl -pe '$. % 2 && chomp'

(The perl just deletes every other newline. You may want to insert a space and add a trailing newline if the last line is an odd number.)

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.