
現在私のテキストファイルは次のとおりです。
David Webb Box 34 Rural Route 2 Nixa MO 65714 (417)555-1478 555-66-7788 09-13-1970
Martha Kent 1122 North Hwy 5 Smallville KS 66789 (785)555-2322 343-55-8845 04-17-1965
Edward Nygma 443 W. Broadway Gotham City NJ 12458 (212)743-3537 785-48-5524 08-08-1987
O'Reilly Baba 123 Torch Ln Joplin MO 64801 (417)222-1234 456-65-3211 12-13-1999
Martin Bob 44 Boss Rd Joplin MO 64801 (417)888-4565 456-98-1111 01-01-2007
January 7, 2017
日付は9番目のフィールドにあります。たとえば、代わりに日付を表示したいと思います01-07-2017
。
どうすればいいですか?オプションを使用する場合は、その機能について簡単に説明してください。 Bashでこれを行います。元のファイルを保存するには、それをスクリプトに入れて新しいファイルとして出力する必要があります。
答え1
これは次の方法で簡単に実行できます。GNU awk時間関数を介して(MK時間そして時間)しかしsedまた、これを行うことができます
sed '
/^[0-9]/{ #for last field with date
y|-|/|
s/^/date +"%B %d, %Y" -d /e #reformat string by date
b #go to end (print)
}
s/\(.*\)\s/\1\n/ #separate last field
P #print string without last field
D #operate just last field from start
' original.file |
paste - - > new.file
答え2
私はあなたがbash / shellスクリプトを要求したことを知っていますが、可能であればPythonでもこれを行うことができます。
# date_converter.py
from datetime import datetime
from sys import stdin, stdout
spt = lambda x: datetime.strptime(x, "%m-%d-%Y")
sft = lambda x: datetime.strftime(x, "%B %d, %Y")
convert = lambda x: sft(spt(x))
for line in stdin.readlines():
stdout.write(line[:-11] + convert(line[-11:-1]) + '\n')
使用法:
python3.5 date_converter.py < old.txt > new.txt