Linux 将每n行转换为一行

Linux 将每n行转换为一行,linux,shell,awk,sed,paste,Linux,Shell,Awk,Sed,Paste,我试着把n行串成一行,不知道怎么做。感谢您的帮助 一堆11个单词,然后是一个空行,然后又是一堆ll单词,然后是空白,比如…等等 例子: 期望输出: 通过awk $ awk -v RS= '{gsub(/\n/, " ")}1' file hi hello how are you i am fine how are you hi how is she doing i have not herd from her 您也可以这样做(虽然有点长): 如果需要在脚本中使用组装好的行,可以在解析文件

我试着把n行串成一行,不知道怎么做。感谢您的帮助

一堆11个单词,然后是一个空行,然后又是一堆ll单词,然后是空白,比如…等等

例子: 期望输出: 通过awk

$ awk -v RS= '{gsub(/\n/, " ")}1' file
hi hello how are you i am fine how are you
hi how is she doing i  have not  herd  from her
您也可以这样做(虽然有点长):


如果需要在脚本中使用组装好的行,可以在解析文件时将每一行存储在一个数组中,以供以后使用:

#!/bin/bash

declare -i cnt=0
declare -a array

while read -r ln; do                            # read each line as ln
    [ "$ln" == "" ] && {                        # test for empty ln
        [ $cnt -gt 0 ] && {                     # if not first empty line
            while [ "${line:0:1}" == ' ' ]; do  # trim leading spaces from line
                line="${line:1}"
            done
            array+=( "$line" )                  # add line to array
            unset line                          # unset line
            continue                            # get next line
        }
        ((cnt++))                               # increment count
    }
    line+=" $ln"                                # append ln to line
done <"$1"
[ ${#line} -gt 0 ] && array+=( "$line" )        # if no trailing blank line

for ((a = 0; a < ${#array[@]}; a++)); do        # output array
    printf " array[%d]: %s\n" "$a" "${array[a]}"
done

exit 0
输出

$ cat dat/bunchw.txt

hi
hello
how
are
you
i
am
fine
how
are
you

hi
how
is
she
doing
i
have
not
herd
from
her
$ bash rdwordsline.sh dat/bunchw.txt
 array[0]: hi hello how are you i am fine how are you
 array[1]: hi how is she doing i have not herd from her

将由空行分隔的文本块视为单个记录在awk中称为段落模式:

$ awk -v RS= '{$1=$1}1' file
hi hello how are you i am fine how are you
hi how is she doing i have not herd from her

所需的输出,但每11个元素转置一次

awk 'ORS=NR%11?FS:RS'

感谢这对我来说效果很好,我不得不在我的文件上使用一次“dos2unix-cscii”来实现这一点。(我的文件有问题)您可以尝试
awk-vrs='{gsub(/[\r\n]+/,“”)}1'文件
$ cat dat/bunchw.txt

hi
hello
how
are
you
i
am
fine
how
are
you

hi
how
is
she
doing
i
have
not
herd
from
her
$ bash rdwordsline.sh dat/bunchw.txt
 array[0]: hi hello how are you i am fine how are you
 array[1]: hi how is she doing i have not herd from her
$ awk -v RS= '{$1=$1}1' file
hi hello how are you i am fine how are you
hi how is she doing i have not herd from her
awk 'ORS=NR%11?FS:RS'