user2656141
user2656141

Reputation: 21

extract content after pattern matching in linux

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

Upvotes: 2

Views: 456

Answers (4)

sigmalha
sigmalha

Reputation: 733

perl method.

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/}'

Output:

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

not so elegant, but it works.

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85765

This awk script will do the trick:

$ 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

Upvotes: 0

Kent
Kent

Reputation: 195029

give grep a try:

grep -o 'heap=.*'

exmaple

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

Upvotes: 1

Adam Siemion
Adam Siemion

Reputation: 16029

grep -o 'heap=[^ ]* node_type=[^ ]*' test
heap=0x100000 node_type=IB
heap=0x256000 node_type=AB

Upvotes: 1

Related Questions