sed または awk を使用して、行の前にファイルプレフィックスを付けます。

sed または awk を使用して、行の前にファイルプレフィックスを付けます。

以下の出力ファイルのようなものを得るために、サンプル入力ファイルをどのように変更しますか?

入力ファイル:

/tmp/ログ
2015年10月13日 00:19:13 温度記録 1
10/13/15 00:19:13 仮想ログ
2015年10月13日01:19:12にテスト済み
2015年10月13日01:19:12エラー
/tmp/エラー
2015年10月13日 00:16:10 x
2015年10月13日 00:16:10
2015年10月13日 01:16:10
2015年10月13日 01:16:10
/tmp/アクセス
2015年10月13日 00:56:14b
2015年10月13日 00:56:14

結果ファイル:

/tmp/log10/13/15 00:19:13 templogs1
/tmp/logs 10/13/15 00:19:13 仮想ログ
/tmp/logs 10/13/15 01:19:12 テスト
/tmp/logs 10/13/15 01:19:12エラー
/tmp/エラー 10/13/15 00:16:10 x
/tmp/エラー 10/13/15 00:16:10 y
/tmp/エラー 10/13/15 01:16:10 z
/tmp/エラー 10/13/15 01:16:10
/tmp/接続 10/13/15 00:56:14 b
/tmp/接続 10/13/15 00:56:14 c

ベストアンサー1

試してみてくださいsed

sed '
    /^\//{                    # execite block if line start with «/»
        h                     # put line into hold-space
        d                     # clean, return to beginning
        }                     # end block
    G                         # append hold-space to line
    s/\(.*\)\n\(.*\)/\2 \1/   # exchange first and last part of line
    ' input.file > output.file

そして他の変形

sed '
    /^\//{                    # execute from line started with «/»
        :1                    # mark return point
        N                     # get next line
        /\n\//D               # if such next line started «/» remove previous
                              #+and starts from the beginning with last line
        s/\n/ /p              # change newline with space and prints both lines
        s/ .*//               # removes last line
        $!b1                  # return to marked point with fist line if not end
        d                     # clean all (finish)
        }
    ' input.file > output.file

おすすめ記事