如何在bash中的N个字符后的每一行中将常量字符串插入到文本文件中

时间:2016-12-02 13:40:15

标签: bash file awk sed

我需要一个bash或awk或sed解决方案,以便在N个空格之后在文件的每一行中插入一个字符串

例如我想要这个文件

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

6 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

在最后一位数字后面插入你的字符串,与sed:

一致
$ sed 's/.*[0-9]/& my_constant_string/' file

答案 4 :(得分: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}仅适用于其他版本的Gnu awk,所以应该:

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

答案 5 :(得分:-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