将每 n 行转置为一行

transpose every n lines into a single line

我正在尝试将 n 行代码合并为一行,但不知道该怎么做。任何帮助表示赞赏。

一堆 11 个单词,然后是一个空白行,然后是一堆 ll 个单词,然后是空白,就像...等等。

示例:

cat filename

hi
hello
how
are
you
i
am
fine
how
are
you

hi
how
is
she
doing
i 
have
not 
herd 
from
her

..
..

期望的输出:

cat newFile

hi hello how are you i am fine how are you 
hi how is she doing i have not heard from her 
..
..

通过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
c=0
while read -r i
do
if [[ $i == "" ]]; then
line="$line""\n"
c=2
elif [[ $c == "2" || $c == "0" ]]; then
line="$line""$i"
c=1
else
line="$line"" ""$i"
fi
done <file1
echo -e "$line"

输出:

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 <""
[ ${#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' 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'