简体   繁体   中英

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.

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
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 (ie you didn't mention bash or ksh , for example).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM