2012-04-18 18 views
0

我需要將.csv文件從一個目錄複製到另一個目錄,同時這樣做需要重新格式化第一列(日期列),從2012年4月13日至2012年4月-13。什麼是執行這種簡單轉換的sed語法?我在網上閱讀的sed內容讓我非常困惑。使用sed複製時的格式化日期列

回答

2

到目前爲止您嘗試過什麼?你可以從一些小事像這樣的測試案例開始:

echo "13/04/2012;Col2;Col3" | sed -E 's#^([^/]+)/([^/]+)/([0-9]+)(.*)#\3-\2-\1\4#' 

s   = substitution command 
#   = start of pattern 
^   = start of line 
([^/]+)/ = group of all non-/-characters followed by a/(day) 
([^/]+)/ = group of all non-/-characters followed by a/(month) 
([0-9]+) = group of at least one digit (year) 
(.*)  = rest of line 
#   = start of replacement 
\3   = backward reference to capture of third group (year) 
\2   = backward reference to capture of second group (month) 
\1   = backward reference to capture of first group (day) 
\4   = backward reference to capture of fourth group (rest of line) 
# end of command 
+0

'sed'(至少地雷/ GNU 4.2.1)要求'\ +',而不是一個普通的'+'。 – Kevin 2012-04-18 20:25:35

+0

@Kevin:不會,如果使用擴展正則表達式(-E)! – Mithrandir 2012-04-18 20:29:16

+0

啊,錯過了'-E'。 – Kevin 2012-04-18 20:53:11

1
sed 's|^\([0-9]\+\)/\([0-9]\+\)/\([0-9]\+\)|\3-\2-\1|' 

這開始於行(^)的開頭,記錄(\(...\))一個或多個(\+)號([0-9])後跟一個斜槓(/),第二組後跟另一個斜線和第三組,並重新排列由破折號分隔的記錄集(\1,\2,\3)。

0

這可能會爲你工作:

sed 's/^\(..\).\(..\).\(....\)/\3-\2-\1/' file