olidev
olidev

Reputation: 20684

sh shell script of working with for loop

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.

Upvotes: 0

Views: 296

Answers (4)

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28010

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).

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247210

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

Upvotes: 3

William Pursell
William Pursell

Reputation: 212664

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.)

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143299

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.

Upvotes: 0

Related Questions