1

I want to extract some content after a matching pattern from a file.

$ cat test
setenv se_boot_opt heap=0x100000 node_type=IB
namedalloc GWUP_FEATURE_MEMORY_BLOCK 0x480000000 0x16093A000
namedprint
setenv se_boot_opt2 heap=0x256000 node_type=AB

I need to process the input file line by line. For each line it need to check the following.

  1. If the line starts with setenv word then it should omit the first 2 words and print/output the remaining content in that line.

  2. If the line starts with namedalloc then it should replace with uboot_namedalloc word.

I want to have only the below lines in my output.

heap=0x100000 node_type=IB
uboot_namedalloc GWUP_FEATURE_MEMORY_BLOCK 0x480000000 0x16093A000
namedprint
heap=0x256000 node_type=AB
4

4 回答 4

1

试试 grep:

grep -o 'heap=.*'

示例

kent$  echo "setenv se_boot_opt1 heap=0x100000 node_type=IB
namedprint
setenv se_boot_opt2 heap=0x256000 node_type=AB"|grep -o 'heap=.*'
heap=0x100000 node_type=IB
heap=0x256000 node_type=AB
于 2013-08-06T09:27:10.577 回答
1
grep -o 'heap=[^ ]* node_type=[^ ]*' test
heap=0x100000 node_type=IB
heap=0x256000 node_type=AB
于 2013-08-06T09:27:24.940 回答
0

这个awk脚本可以解决问题:

$ awk '$1=="setenv"{$1=$2="";sub(/ */,"")}$1=="namedalloc"{$1="uboot_"$1}1' file
heap=0x100000 node_type=IB
uboot_namedalloc GWUP_FEATURE_MEMORY_BLOCK 0x480000000 0x16093A000
namedprint
heap=0x256000 node_type=AB
于 2013-08-06T09:33:13.663 回答
0

perl 方法。

echo 'setenv se_boot_opt heap=0x100000 node_type=IB
namedalloc GWUP_FEATURE_MEMORY_BLOCK 0x480000000 0x16093A000
namedprint
setenv se_boot_opt2 heap=0x256000 node_type=AB' | perl -lape 'if (/^setenv/){s/(\w+\s){2}//}elsif(/^namedalloc/){s/namedalloc/uboot_namedalloc/}'

输出:

heap=0x100000 node_type=IB
uboot_namedalloc GWUP_FEATURE_MEMORY_BLOCK 0x480000000 0x16093A000
namedprint
heap=0x256000 node_type=AB

不是那么优雅,但它的工作原理。

于 2013-08-06T12:17:39.093 回答