Bash 脚本中的字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7918098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:00:21  来源:igfitidea点击:

String concatenation in Bash script

bashshell

提问by olidev

I am writing this Bash script:

我正在编写这个 Bash 脚本:

count=0   
result

for d in `ls -1 $IMAGE_DIR | egrep "jpg$"`
do

    if (( (count % 4) == 0 )); then
                result="abc $d"

                if (( count > 0 )); then
                    echo "$result;"
                fi

        else
            result="$result $d"
        fi

        (( count++ ))

done

if (( (count % 4) == 0 )); then
    echo $result
fi

The script is to concate part strings into a string when the value is divided by 4 and it should be larger than 0.

该脚本是将部分字符串在值除以 4 并且应该大于 0 时连接成一个字符串。

In the IMAGE_DIR, I have 8 images,

在 IMAGE_DIR 中,我有 8 张图片,

I got outputs like this:

我得到了这样的输出:

abc et004.jpg
abc et008.jpg

But I would expect to have:

但我希望有:

abc et001.jpg et002.jpg et003.jpg et004.jpg;
abc et005.jpg et006.jpg et007.jpg et008.jpg;

How can I fix this?

我怎样才能解决这个问题?

回答by Kilian Foth

The =operator must always be written without spaces around it:

=操作必须写入的周围没有空格:

result="$result $d"

(Pretty much the most important difference in shell programming to normal programming is that whitespace matters in places where you wouldn't expect it. This is one of them.)

(在 shell 编程与普通编程中最重要的区别几乎是空白在你意想不到的地方很重要。这是其中之一。)

回答by Kusalananda

Something like this?

像这样的东西?

count=0   

find $IMAGE_DIR -name "*.jpg" |
while read f; do
        if (( (count % 4) == 0 )); then
                result="abc $f"

                if (( count > 0 )); then
                        echo $result
                fi

        else
                result="$result $d"
        fi

        (( count++ ))
done

回答by Dimitre Radoulov

Something like this (untested, of course):

像这样的东西(当然未经测试):

count=0 result=

for d in "$IMAGE_DIR"/*jpg; do
   (( ++count % 4 == 0 )) &&
     result="abc $d"
   (( count > 0 )) &&
     printf '%s\n' "$result" ||
      result+=$d
done