ファイルの日付出力の変更

ファイルの日付出力の変更

2008年4月26日txtファイルのエントリを2008年4月に変換したいと思います。

注:これはdateコマンドを使用せず、ファイルの日付エントリです。

sedを使用してこれを実行できますか?

これはパイプなどを使用する一行スクリプトの一部です。

ベストアンサー1

sedいいえ、プロセスは日付を解析する必要があるため機能しません。

コマンドの組み合わせを使用してこれを実行できますdate。または、個人的には次のようにperl使用できます。これは可能ですが、日付解析を実行するモジュールsedもあります。Time::Piece

実行可能な例:

#!/usr/bin/env perl
use strict;
use warnings;

use Time::Piece; 

while ( <DATA> ) {
   chomp; 
   print Time::Piece->strptime($_, "%d/%m/%Y")->strftime("%B %Y"),"\n";
}

__DATA__
26/04/2008
26/05/2008
26/07/2009

パイプラインで「1つのライナー」として使用できます(または最後にパラメーターとして処理するファイルを指定できます)。

perl -MTime::Piece -nle 'print Time::Piece->strptime($_, "%d/%m/%Y")->strftime("%B %Y");'

注 – どちらも日付が 1 行に 1 つしかないと仮定します。必要に応じて部分文字列として抽出することは特に難しくなく、部分文字列パターンとして効果的に「sed」することができる。

#!/usr/bin/env perl
use strict;
use warnings;

use Time::Piece; 

while ( <DATA> ) {
   s|(\d{2}/\d{2}/\d{4})|Time::Piece->strptime($1, "%d/%m/%Y")->strftime("%B %Y")|e;
   print;
}

__DATA__
26/04/2008 and some text here 
a line like this with a date of 26/05/2008 
26/07/2009 and some more here maybe 

次のように変わります。

April 2008 and some text here 
a line like this with a date of May 2008 
July 2009 and some more here maybe

もう一度行は次のようになります。

perl -MTime::Piece -pe 's|(\d{2}/\d{2}/\d{4})|Time::Piece->strptime($1, "%d/%m/%Y")->strftime("%B %Y")|e;'  

おすすめ記事