2016-12-02 68 views
0

N個字符插入一個常量字符串到一個文本文件中的每一行,我需要爲了一個bash或AWK或sed的解決方案插入一個文件的每一行的字符串,在N空間後如何在bash

例如,我想這個文件

Nov 30 23:09:39.029313 sad asdadfahfgh 
Nov 30 23:09:39.029338 ads dsfgdsfgdf 
Nov 30 23:09:46.246912 hfg sdasdsa 
Nov 30 23:09:46.246951 jghjgh dfgdfgdf 

Nov 30 23:09:39.029313 my_constant_string sad asdadfahfgh 
Nov 30 23:09:39.029338 my_constant_string ads dsfgdsfgdf 
Nov 30 23:09:46.246912 my_constant_string hfg sdasdsa 
Nov 30 23:09:46.246951 my_constant_string jghjgh dfgdfgdf 

我嘗試以下但不工作:

awk '{print $2" "$3" "$4" crit { for(i=5;i<NF;i++) print $i}}' log_file 
+0

發表您嘗試 –

+0

我想貓LOG_FILE | awk'{print $ 2''$ 3''$ 4'crit {for(i = 5; i sotiris

回答

2

與GNU sed

$ sed 's//xxx /3' file 

Nov 30 23:09:39.029313 xxx sad asdadfahfgh 
Nov 30 23:09:39.029338 xxx ads dsfgdsfgdf 
Nov 30 23:09:46.246912 xxx hfg sdasdsa 
Nov 30 23:09:46.246951 xxx jghjgh dfgdfgdf 
+0

這很聰明!你可以說'sed's /./& HELLO/23'文件',因爲它會在第23個字符後面加上「HELLO」。 – fedorqui

1

你可以使用這個;

awk '{$4="my_constant_string "$4; print $0}' yourFile 

awk '{for (i=1;i<=3;i++) printf "%s ", $i ;printf "my_constant_string " ; for (i=4;i<=NF;i++) printf "%s ", $i; printf "\n" }' 

測試

$ awk '$4="my_constant_string " $4' test 
Nov 30 23:09:39.029313 my_constant_string sad asdadfahfgh 
Nov 30 23:09:39.029338 my_constant_string ads dsfgdsfgdf 
Nov 30 23:09:46.246912 my_constant_string hfg sdasdsa 
Nov 30 23:09:46.246951 my_constant_string jghjgh dfgdfgdf 
+3

'awk'$ 4 =「my_constant_string」$ 4'文件' – Kent

+1

不,你不需要更新,你原來的答案很容易理解,我在評論中提供的是一個技巧,如果OP想添加一個字符串「0」,那麼它可能會失敗,所以你的答案很好。 – Kent

1

如果你想有一個固定數目的字符後添加內容,而不是在一個特定的列,使用sed

sed -r 's/^.{23}/&HELLO /' file 

sed 's/^.\{23\}/&HELLO /' file # equivalent, without -r 

這捕獲了噸他在線上的第23個字符並將其打印回來。

這將返回:

Nov 30 23:09:39.029313 HELLO sad asdadfahfgh 
Nov 30 23:09:39.029338 HELLO ads dsfgdsfgdf 
Nov 30 23:09:46.246912 HELLO hfg sdasdsa 
Nov 30 23:09:46.246951 HELLO jghjgh dfgdfgdf 
0

要行最後一位與sed的後面插入你的字符串:

$ sed 's/.*[0-9]/& my_constant_string/' file 
-1
awk '{print $1,$2,$3,"my_constant_string",$4,$5}' file 

Nov 30 23:09:39.029313 my_constant_string sad asdadfahfgh 
Nov 30 23:09:39.029338 my_constant_string ads dsfgdsfgdf 
Nov 30 23:09:46.246912 my_constant_string hfg sdasdsa 
Nov 30 23:09:46.246951 my_constant_string jghjgh dfgdfgdf 
0

使用了GNU AWK你可以:

$ awk 'sub(/^.{22}/, "& my_constant_string")' file 
Nov 30 23:09:39.029313 my_constant_string sad asdadfahfgh 
Nov 30 23:09:39.029338 my_constant_string ads dsfgdsfgdf 
Nov 30 23:09:46.246912 my_constant_string hfg sdasdsa 
Nov 30 23:09:46.246951 my_constant_string jghjgh dfgdfgdf 

由於正則表達式.{22}只牛羚與其他版本的一個工作應該AWK:

$ awk 'sub(/^....................../, "& my_constant_string")' file