Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating a file using bash script

Tags:

bash

shell

unix

sed

I have the following file:

RATL_EXTRAFLAGS := -DRATL_REDHAT -DRATL_VENDOR_VER=601 -DRATL_EXTRA_VER=0
LINUX_KERNEL_DIR=/lib/modules/2.6.32-279.el6.i686/build
CONFIG_MVFS=m

Assuming that the file name is testFile I'd like to know how get the value of LINUX_KERNEL_DIR and how can I change it in case I need?

Another thing how can I check what is the value of -DRATL_VENDOR_VER and also how can I change the value in case I need to do that?

I'll prefer to get an answer using sed.

like image 664
Alex Brodov Avatar asked Feb 05 '26 05:02

Alex Brodov


2 Answers

You can use this awk command:

awk -F= '$1=="LINUX_KERNEL_DIR"{print $2}' "$file"
/lib/modules/2.6.32-279.el6.i686/build

This awk command sets input field separator as = so that text before = can be accessed using $1 and value after = using $2. When $1 == "LINUX_KERNEL_DIR" it prints $2.

Based on your comments you can do:

awk -F '[= ]' '{for (i=1; i<=NF; i+=2) if($i=="-DRATL_VENDOR_VER") { print $(i+1); break}}
    $1=="LINUX_KERNEL_DIR"{print $2}' file
601
/lib/modules/2.6.32-279.el6.i686/build
like image 178
anubhava Avatar answered Feb 06 '26 18:02

anubhava


This will yield the value of LINUX_KERNEL_DIR using sed as you preferred:

sed -n '/LINUX_KERNEL_DIR/p' testFile | sed 's/.*=//'

Also, if you want the value of -DRATL_VENDOR_VER:

sed -n '/-DRATL_VENDOR_VER/p' testFile | sed 's/.*DRATL_VENDOR_VER=\([0-9]*\).*/\1/g'

Moreover, if you want to change the value of, for example, LINUX_KERNEL_DIR, you can use this script:

file=$1
pattern=$(sed -n '/LINUX_KERNEL_DIR/p' $file | sed 's/.*=//')
sed s,$pattern,whatever, $file

The same procedure works if you want to change the value of DRATL_VENDOR_VER, all you have to change is the pattern variable.

Be aware, if the variable pattern contains backslashes, you need to use a different separator in your sed command, in this case I used ,

like image 24
buydadip Avatar answered Feb 06 '26 18:02

buydadip