
次の内容を含むファイルがあります。
ファイル.txt:
661###############20160315###
###########################
###########################
661###############20160316###
###########################
661###############20160317###
###########################
この単一ファイルを開始文字列「661」と日付(2016MMDD)に基づいて複数のファイルに分割し、分割ファイルの名前を20160315.txt、20160316.txtなどに変更したいと思います。たとえば、各分割ファイルには次のものが含まれます。
20160315.txt には以下が含まれます。
661###############20160315########
################################
################################
20160316.txt には以下が含まれます。
661###############20160316########
################################
20160317.txt には以下が含まれます。
661###############20160317#######
###############################
これを実行できるawkコマンドはありますか?
答え1
これを行うためのコマンドがあると確信していますが、解決策を提示するのに十分awk
熟練していません。awk
その間、次のように使用できます。
#!/bin/bash
csplit -z tosplit /661/ {*}
for file in xx*; do
newName=$(egrep -o '2[0-9]{7}' $file)
mv $file $newName.txt
done
rm -rf xx*
このファイルtosplit
(例ファイル)はどこにありますか?
661###############20160315###
###########################
###########################
661###############20160316###
###########################
661###############20160317###
###########################
このスクリプト(filesと同じディレクトリにありますtosplit
)を実行すると、3つのファイルが生成されます。
ls 2016031*
20160315.txt 20160316.txt 20160317.txt
...次のようになります。
cat 20160315.txt
661###############20160315###
###########################
###########################
cat 20160316.txt
661###############20160316###
###########################
cat 20160317.txt
661###############20160317###
###########################
ファイル名を指定(?)することもできますが、csplit
それも私の給料を越えることです!
答え2
awk
同様に
awk '/^661/{f=substr($0,match($0,/2016[0-9]{4}/),8)".txt"}{print>>f}' file.txt
あなたに適しているかもしれません。
デフォルトでは、部品は次のとおりです。
/^661/{...} # on each line starting with 661
match($0,/2016[0-9]{4}/) # find the index of the date (2016MMDD) in current line
substr($0,match($0,/2016[0-9]{4}/),8) # extract the the date in the current line
f=substr($0,match($0,/2016[0-9]{4}/),8)".txt" # assign it to f and append ".txt"
{print>>f} # redirect the content of the current line into the file named by f
従来awk
の実装では、交換が必要な場合があります。間隔表現到着する:
awk '/^661/{f=substr($0,match($0,/2016[01][0-9][0-9][0-9]/),8)".txt"}{print>>f}' file.txt
ユースケースに応じて変更したい場合があります。リダイレクト動作つまりprint>f
、print>>f