Shell脚本用于查找文件中最后出现的行ID并添加新行

时间:2014-07-25 11:53:14

标签: bash sed

我有一个文本文件,格式如下:

abc
def
...
...
ID=1
This is Entry1
ID=2
This is Entry2
...
ID=<N>
This is Entry<N>
xyz
...

如何在“xyz”行之前将以下新条目插入文本文件?

ID=N+1
This is Entry<N+1>

更复杂的是,ID行可能不在文件中,因此订单可能是:

abc
def
...
ID=5
ID=2
ID=N
...
ID=9
...
xyz

(其中N = 10,最高)。

有没有办法识别文件中出现最高(数字)ID行的内容,然后在“xyz”行出现之前添加新行“ID =”?

提前致谢!

5 个答案:

答案 0 :(得分:1)

awk的另一种方式

awk -F= '/ID=/{x=$2>x?$2:x}FNR==NR{next}
/xyz/{print "ID="x+1"\nThis is entry<"x+1">"}1' test{,}

答案 1 :(得分:0)

我猜你正在寻找这个:

awk -F'=' 'NR==FNR{if(/^ID=/)n=$2>n?$2:n;next}
           /^xyz$/{print "ID="++n;printf "whatEVER<%d>\n",n}7' file file

见这个例子:

kent$  cat f
abc
def
ID=5
ID=2
foo
ID=777
bar
ID=9
xyz


kent$  awk -F'=' 'NR==FNR{if(/^ID=/)n=$2>n?$2:n;next}/^xyz$/{print 
"ID="++n;printf "whatEVER<%d>\n",n}7' f f
abc
def
ID=5
ID=2
foo
ID=777
bar
ID=9
ID=778
whatEVER<778>
xyz

答案 2 :(得分:0)

首先获得最大值:

val=$(grep -Po '(?<=ID=)\d*' file | sort -n | tail -1)

然后在行xyz之前打印:

awk -v d="$val" '/xyz/ {print "This is entry", d+1} 1' file

要更新文件,请重定向到临时文件,然后在未找到错误时重写:

awk -v d="$val" '/xyz/ {print "This is entry", d+1} 1' file > tmp_file && mv tmp_file file

测试

$ cat a
abc
def
...
...
ID=1
This is Entry1
ID=2
This is Entry2
...
ID=9
xyz
ID=23
alsjdflk
ID=2
$ d=$(grep -Po '(?<=ID=)\d*' a | sort -n | tail -1)
$ awk -v d="$d" '/xyz/ {print "This is entry", d+1} 1' a
abc
def
...
...
ID=1
This is Entry1
ID=2
This is Entry2
...
ID=9
This is entry 24
xyz
ID=23
alsjdflk
ID=2

请参阅grep | sort | tail命令的实现:

$ grep -Po '(?<=ID=)\d*' a 
1
2
9
23
2
$ grep -Po '(?<=ID=)\d*' a | sort -n
1
2
2
9
23
$ grep -Po '(?<=ID=)\d*' a | sort -n | tail -1
23

答案 3 :(得分:0)

你可以获得最高的数字:

highest=$(sed -n '/^ID=/s/^ID=//p' filename | sort -nr | head -1)
new=$((highest + 1))

然后将其插入文件:

sed -i .bak "/xyz/i\
ID=$new\
This is entry$new\
" filename

答案 4 :(得分:0)

  

确定文件中出现最高(数字)ID行的内容,然后在出现“xyz”行之前添加新行“ID =”?   
[...]
  ID行可能不在文件

怎么样:

awk -F = '$1=="ID" { if($2>ID) ID=$2 }
          /^xyz/    { printf("ID=%d\nThis is entry%d\n",ID+1,ID+1) }
          1' testfile

以下是一个用法示例:

sh$ cat testfile
abc
def
...
...
ID=1
This is Entry1
ID=55
This is Entry55
...
ID=3
This is Entry3
xyz
...
sh$ awk -F = '$1=="ID" { if($2>ID) ID=$2 } /^xyz/ { printf("ID=%d\nThis is entry%d\n",ID+1,ID+1) } 1' testfile
abc
def
...
...
ID=1
This is Entry1
ID=55
This is Entry55
...
ID=3
This is Entry3
ID=56
This is entry56
xyz
...