簡體   English   中英

使用Sed減少日期的秒數

[英]Use Sed to cut out the seconds from a date

我在文件中有一個url數據列表,如下所示:

    http://site.com/some/site.htm,12/5/2012 3:30:39 PM
    http://site.com/some/site.htm,12/5/2012 9:30:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30:39 AM

我希望它看起來像這樣:

    http://site.com/some/site.htm,12/5/2012 3:30 PM
    http://site.com/some/site.htm,12/5/2012 9:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30 AM

基本上使用sed從行中刪除:XX秒部分。 我也不介意它是否會在會議記錄后刪除所有內容。 我可以使用sed或cut,因為我正在使用批處理文件腳本。 有人可以幫忙嗎?

到目前為止,我已經嘗試了以下內容:

sed 's/.*:([^,*]*) AM/\1/g' file.txt

像這個sed -r 's/(.*):[0-9]{2}(.*)/\\1\\2/'

$ cat file
    http://site.com/some/site.htm,12/5/2012 3:30:39 PM
    http://site.com/some/site.htm,12/5/2012 9:30:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30:39 AM

$ sed -r 's/(.*):[0-9]{2}(.*)/\1\2/' file
    http://site.com/some/site.htm,12/5/2012 3:30 PM
    http://site.com/some/site.htm,12/5/2012 9:30 AM
    https://site.com/some/site.htm,12/5/2012 13:30 PM
    http://site.com/some/site.htm,12/5/2012 10:30 AM

說明:

(.*):     # Capture everything up the last : (greedy)
[0-9]{2}  # Match the two digits 
(.*)      # Capture the rest of the line

\1\2      # Replace with the two captured groups

注意: -r使用擴展的正則表達式,可能是-E依賴於你的sed風味,請與man檢查。

編輯:

$ sed -r 's/[0-9]{2}:[0-9]{2} /00 /' file
    http://site.com/some/site.htm,12/5/2012 3:00 PM
    http://site.com/some/site.htm,12/5/2012 9:00 AM
    https://site.com/some/site.htm,12/5/2012 13:00 PM
    http://site.com/some/site.htm,12/5/2012 10:00 AM

一個簡單的解決方案,只需在冒號后面跟一個空格查找2位數,然后只用空格替換。

sed 's/:[0-9][0-9] / /g' file.txt

一個非常簡單的解決方

sed 's/:.. / /' file

但這可能不推薦,因為它過於通用,如果格式化甚至略有變化,可能會出錯。

替代解決方案:

sed -r 's/...( [AP]M)$/\1/' file.txt

以空格結尾的行匹配,后跟AM或PM,並刪除前面的三個字符。

行尾的$匹配,括號保留AMPM因此您可以使用替換文本中的\\1引用它。 -r命令行選項允許使用擴展正則表達式( \\1引用所需)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM