各行に特定の単語を追加する

各行に特定の単語を追加する

ここにはfile.txtのようなファイルがあります。

bbb-ccc-cccc#
   aasdf  asdas asdasa fgdg
   asdfa  asfdas  adfaq  asfa
   afdaf  fafa  fafd  afafa
bbb-ccc-cccc#

#次に終わる単語を取り、各行の最初の単語として追加したいと思います。

sed 's/bbb-ccc-cccc#/^/' < file.txt > newfile.txt

#記号の前の単語を事前に知らないので、私のポイントはで終わる単語を見つけて各行の先頭#に入れることです。この file.txt には次のものが必要です。

bbb-ccc-cccc#
bbb-ccc-cccc#   aasdf  asdas asdasa fgdg
bbb-ccc-cccc#   asdfa  asfdas  adfaq  asfa
bbb-ccc-cccc#   afdaf  fafa  fafd  afafa
bbb-ccc-cccc#

ベストアンサー1

そしてperl

perl -lpe 'if (/\H+#/) {$word = $&} else {$_ = $word . $_}'

つまり、1行で空白以外の文字(\H+)の後にaが続く場合は、そのシーケンス(正規表現に一致するもの)を次の行の先頭に挿入する単語として使用します。#$&

awk同じ

awk '
  match($0, /[^[:blank:]]+#/) {
    word = substr($0, RSTART, RLENGTH)
    print
    next
  }
  {print word $0}'

sed(使用してスペアスペース保存する言葉):

sed '
  /[^[:blank:]]\{1,\}#/ {
    h; # save the line in the hold space
    s//\
&\
/; # put newlines on each side of the matched word
    s/.*\n\(.*\)\n/\1/; # remove every thing but the word
    x; # swap hold and pattern space so that now the hold
       # space contains the word. And branch off:
    b
  }
  # for the other lines:
  G; # append the hold space to the pattern space
  s/\(.*\)\n\(.*\)/\2\1/; # move the word to the beginning'

word#行の終わりにのみsを一致させるには、上記の3つのコマンドをすべてwithに置き換えます##$

おすすめ記事