复制包含单个单词的行并将其粘贴到以下行?

时间:2018-12-24 09:29:26

标签: bash awk sed

请在下面的示例中查看详细信息,其中将多个单词粘贴到单行单词中

targetsdkversion

需要

word1
multiple word hello hi
multiple word hi bye
multiple word ok done
word2
multiple word ok bye
multiple word sldfjkdfs sd f
word3
multiple word

3 个答案:

答案 0 :(得分:2)

def polynomial_features(data, deg):
    data_copy=data.copy()
    #print(data_copy.head())
    for i in range(1,deg):
        data_copy['X'+str(i+1)]=data_copy['X'+str(i)]*data_copy['X1']
    return data_copy

x_pred = pd.Series({'X1':[i/200.0 for i in range(200)]})
y_pred = model.predict(polynomial_features(x_pred,deg))

cat file #=> word1 #=> multiple word hello hi #=> multiple word hi bye #=> multiple word ok done #=> word2 #=> multiple word ok bye #=> multiple word sldfjkdfs sd f #=> word3 #=> multiple word 解决方案:

awk

awk 'NF==1{lastword=$1}NF>1{print lastword,$0}' file #=> word1 multiple word hello hi #=> word1 multiple word hi bye #=> word1 multiple word ok done #=> word2 multiple word ok bye #=> word2 multiple word sldfjkdfs sd f #=> word3 multiple word 代表列号(此处为单词数字),
NF保存单个单词。
lastword表示有多个单词。

NF>1解决方案(GNU sed):

sed

它使用sed -nr '/^[^ \t]+$/h;/^[^ \t]+[ \t]+[^ \t]+/{G;s/(.*)\n(.*)/\2 \1/;p}' file #=> word1 multiple word hello hi #=> word1 multiple word hi bye #=> word1 multiple word ok done #=> word2 multiple word ok bye #=> word2 multiple word sldfjkdfs sd f #=> word3 multiple word 存储单个单词,
然后附加到多个单词行并切换。
hold space用模式空间覆盖保留空间的内容。
h将保留空间的内容追加到模式空间, 用换行符分隔它们。

答案 1 :(得分:0)

这可能对您有用(GNU sed):

sed '/^\S\+$/h;//d;G;s/\(.*\)\n\(.*\)/\2 \1/' file

答案 2 :(得分:0)

这是Perl解决方案

/tmp> cat vgrs.txt
word1
multiple word hello hi
multiple word hi bye
multiple word ok done
word2
multiple word ok bye
multiple word sldfjkdfs sd f
word3
multiple word
/tmp> perl -lne  ' /^(\S+)$/ and $x=$1 ; print "$x $_" if /\s/ ' vgrs.txt
word1 multiple word hello hi
word1 multiple word hi bye
word1 multiple word ok done
word2 multiple word ok bye
word2 multiple word sldfjkdfs sd f
word3 multiple word
/tmp>