Manipulating a file with a bash script
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 the filename testFile
I would like to know how to get the value LINUX_KERNEL_DIR
and how to change it if needed?
One more thing, how can I check what the value -DRATL_VENDOR_VER
is and also how can I change the value in case I need to do this?
I would rather get the answer using sed
.
source to share
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 command awk
sets the input field separator as =
so that the text before =
can be retrieved with $1
and the value after =
with $2
. When he $1 == "LINUX_KERNEL_DIR"
prints $2
.
Based on your comments, you can:
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
source to share
This will give the value LINUX_KERNEL_DIR
using sed as you prefer:
sed -n '/LINUX_KERNEL_DIR/p' testFile | sed 's/.*=//'
Also, if you want a value -DRATL_VENDOR_VER
:
sed -n '/-DRATL_VENDOR_VER/p' testFile | sed 's/.*DRATL_VENDOR_VER=\([0-9]*\).*/\1/g'
Also, if you want to change the value, 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
This same procedure works if you want to change the value DRATL_VENDOR_VER
, all you need to change is the variable pattern
.
Remember that if the variable pattern
contains a backslash you need to use a different separator in the sed command, in this case I used,
source to share
To print the value in LINUX_KERNEL_DIR
sed -n '/LINUX_KERNEL_DIR/s/LINUX_KERNEL_DIR=//p' testFile
find the line with the pattern LINUX_KERNEL_DIR
and then remove "LINUX_KERNEL_DIR/s/LINUX_KERNEL_DIR="
and the result is only the value
To print the value DRATL_VENDOR_VER
sed -n '/RATL_EXTRAFLAGS/s/.*-DRATL_VENDOR_VER=\([0-9]*\).*/\1/p' testFile
To print both of the above values ββat the same time
sed -n '/RATL_EXTRAFLAGS/s/.*-DRATL_VENDOR_VER=\([0-9]*\).*/\1/p;/LINUX_KERNEL_DIR/s/LINUX_KERNEL_DIR=//p' testFile
To change the value DRATL_VENDOR_VER
sed -i '/RATL_EXTRAFLAGS/s/-DRATL_VENDOR_VER=[0-9]*/-DRATL_VENDOR_VER=YOUR_VALUE_HERE/g' testFile
where YOUR_VALUE_HERE
represents your value.
source to share