Linux

如何在第一次出現:和冒號之間提取字元串

  • October 11, 2018

我有一個長文件,需要重新處理才能將其輸入數據庫。該文件的數據採用以下格式:

Error for: 111.222.55.1,[ZXX: Error message] some text (_xxx.c:833)
Error for: 198.243.55.25,[ZXX: Error message] some text (_xxx.c:833)
Unexpected error for: 198.245.175.52,[Errno 104] some text here

我需要重新安排文件是這樣的:

Error for,111.222.55.1,[ZXX: Error message] some text (_xxx.c:833)
Error for,198.243.55.25,[ZXX: Error message] some text (_xxx.c:833)
Unexpected error for,198.245.175.52,[Errno 104] some text here
  1. 請注意單詞後面有一個空格for:
  2. 如範例中所示,該字元:可以在一行中出現多次。所以我需要替換之後的第一次出現for:[space]

我想到了sed搜尋和替換。但是不知道如何限制搜尋我想要的位置?

使用 SED:

sed -e 's/: /,/' file > newFile

Error for,111.222.55.1,[ZXX: Error message] some text (_xxx.c:833)
Error for,198.243.55.25,[ZXX: Error message] some text (_xxx.c:833)
Unexpected error for,198.245.175.52,[Errno 104] some text here
  • 預設情況下,sed替換第一次出現。

awk解決方案:

awk '{sub(/: /,",")}1' file


Error for,111.222.55.1,[ZXX: Error message] some text (_xxx.c:833)
Error for,198.243.55.25,[ZXX: Error message] some text (_xxx.c:833)
Unexpected error for,198.245.175.52,[Errno 104] some text here

引用自:https://unix.stackexchange.com/questions/473318