[英]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: 我正在使用sh shell脚本读取文件夹的文件并在屏幕上显示:
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 文件file1.jpg
file file2.jpg 文件file2.jpg
file file3.jpg 文件file3.jpg
file file4.jpg 文件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; 文件file1.jpg; file file2.jpg; 文件file2.jpg;
file file3.jpg; 文件file3.jpg; file file4.jpg; 文件file4.jpg;
In other languages, I just put d++ but it does not work with this case. 在其他语言中,我只使用了d ++,但在这种情况下不起作用。
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: 让Shell为您做更多的工作:
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. 将n设置为所需的任何值。 If you're on Solaris , use nawk or /usr/xpg4/bin/awk (do not use /usr/bin/awk ). 如果您使用的是Solaris ,请使用nawk或/ usr / xpg4 / bin / awk (请勿使用/ 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). 还要注意,鉴于您的问题与sh有关(例如,您没有提及bash或ksh ),我正在尝试使用标准的shell语法。
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. (其中n=1
)进入循环。
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.) (perl只会删除所有其他换行符。如果最后一行是奇数,则可能要插入空格并添加尾随的换行符。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.