在bash中每两个字段打印一个逗号

时间:2014-11-12 14:31:20

标签: bash loops printing awk

例如,我有一个名单列表(第一个和最后一个):

Tom Smith Mary Brown Harry Anderson Sally Hall

我想将其输出为:

Tom Smith, Mary Brown, Harry Anderson, Sally Hall

如果我/你可以在" last"之后输入 '和 ,则可获得积分。逗号。

现在我知道我可以把它扔进for循环并打印并迭代并检查是否有三个字段从结尾到结尾,但我认为必须有一个更简单的方法使用awk或其他命令。

有什么想法吗?

6 个答案:

答案 0 :(得分:4)

只需使用sed

$ sed -r 's/(\w* \w*) /\1, /g' <<< "Tom Smith Mary Brown Harry Anderson Sally Hall"
Tom Smith, Mary Brown, Harry Anderson, Sally Hall

这将选择一组由两个空格分隔的单词,并用逗号将其打印回来。

要打印and而不是最后一个逗号,请在最后一个逗号之前抓取所有内容并使用文本and将其打印回来:

$ sed -r -e 's/(\w* \w*) /\1, /g' -e 's/, ([^,]*)$/ and \1/' <<< "Tom Smith Mary Brown Harry Anderson Sally Hall" 
Tom Smith, Mary Brown, Harry Anderson and Sally Hall

答案 1 :(得分:1)

$ awk '{for (i=1;i<(NF-2);i+=2) printf "%s %s, ", $i, $(i+1); print "and", $(NF-1), $NF}' file
Tom Smith, Mary Brown, Harry Anderson, and Sally Hall

答案 2 :(得分:1)

以为我会添加另一个awk

awk '{while(++i<NF-2)printf "%s",$i (i%2?FS:", ");print $i" and "$++i,$NF}'

Tom Smith, Mary Brown, Harry Anderson and Sally Hall

如果你想在和

之前使用逗号
awk '{while(++i<NF-1)printf "%s",$i (i%2?FS:", ");print "and "$i,$NF}'
Tom Smith, Mary Brown, Harry Anderson,and Sally Hall

否和

 awk '{while(++i<NF)printf "%s",$i (i%2?FS:", ");print $NF}'
 Tom Smith, Mary Brown, Harry Anderson, Sally Hall

最后是我和anubhavas的混合

 awk '{while((i+=2)<NF-1)$i=$i","}--i&&$i="and "$i'

答案 3 :(得分:0)

使用awk:

s='Tom Smith Mary Brown Harry Anderson Sally Hall'
awk '{for (i=2; i<NF-1; i+=2) $i = $i ","; $(NF-1)="and " $(NF-1)} 1' <<< "$s"
Tom Smith, Mary Brown, Harry Anderson, and Sally Hall

答案 4 :(得分:0)

使用awk

echo "Tom Smith Mary Brown Harry Anderson Sally Hall
1 2 3 4" | awk '{for (i=1;i<NF-2;i+=2){printf("%s %s, ", $i, $(i+1)) };print "and "$(NF-1), $NF;}'

Tom Smith, Mary Brown, Harry Anderson, and Sally Hall
1 2, and 3 4

答案 5 :(得分:0)

一个相当简单的方法,使用set

set -- Tom Smith Mary Brown Harry Anderson Sally Hall
while (($#)); do
    printf '%s %s' "$1" "$2"
    shift 2 || shift
    if (($#>2)); then printf ', '; elif (($#)); then printf ' and '; fi
done
printf '\n'

这样你就可以将所有这些放在一个很好的功能中:

sep_them() {
    while (($#)); do
        printf '%s %s' "$1" "$2"
        shift 2 || shift
        if (($#>2)); then printf ', '; elif (($#)); then printf ' and '; fi
    done
    printf '\n'
}

并使用它:

gniourf$ sep_them one
one 
gniourf$ sep_them one two
one two
gniourf$ sep_them one two three
one two and three 
gniourf$ sep_them one two three four
one two and three four
gniourf$ sep_them one two three four five
one two, three four and five 
gniourf$ sep_them one two three four five six
one two, three four and five six
gniourf$ sep_them one two three four five six seven
one two, three four, five six and seven 
gniourf$ sep_them one two three four five six seven eight
one two, three four, five six and seven eight
gniourf$ sep_them one two three four five six seven "eight with a space"
one two, three four, five six and seven eight with a space