简体   繁体   中英

How to Use “sed” Bash Command

I am having difficulties replacing a string in c program file with the content of a variable in a bash file. The idea is to copy the address of Linux kernel sys_call_table and then use it in my C program to intercept system calls. I found a couple of examples online, but none of them have worked for me so far. So any help will be greatly appreciated.

Here is the content of my bash file, "bashFile.sh"

    TABLE=$(grep sys_call_table /boot/System.map-$(uname -r) |awk '{print $1}')
    sed -i "s/myTABLE/{$TABLE}/g" my_LKM.c

When I run "sudo sh bashFile.sh" command, nothing happen. The string myTable in C file does not get replaced. However, when I try the following variation:

    TABLE=$(grep sys_call_table /boot/System.map-$(uname -r) |awk '{print $1}')
    sed -i 's/myTABLE/{$TABLE}/g' my_LKM.c

the myTABLE string get replaced with {$TABLE} instead of the content of the variable TABLE (sys_call_table address). I tried debugging with "echo $TABLE" to see if TABLE content is the address of sys_call_table and it worked. So, I concluded that the problem might be the syntax of sed command. However, I do not know how to fix it at this time. Thank you in advance for your help.

PS Below is the content of myLKM.c file:

    unsigned long *sys_call_table;  
    sys_call_table = (unsigned long *)myTABLE;

First of all, don't use sudo to run this. It doesn't magically make things work. If you need root privileges to edit source code you're working on, you have serious problems with your development setup.


Use double-quotes if you want stuff to expand inside them. eg

TABLE=$(awk '/sys_call_table/ {print $1}' /boot/System.map-$(uname -r))
sed -i "s/myTABLE/${TABLE}UL/g" my_LKM.c

As karakfa suggested, make sure you try this without -i first. His other suggestion, of expanding $TABLE in an unquoted context, instead of inside double quotes, was terrible, though. You need the entire string to be part of the same sed arg, so just ending the single quotes is bad.

Also, I guess he misread {$TABLE} for ${TABLE} , and simplified to $TABLE . Or actually, from the context of your question, it looks like you want a plain numeric constant, not wrapped in braces. So you should use $TABLE .

Actually, you should use ${TABLE}UL so it's an unsigned-long integer literal. Without those modifiers, an address that didn't fit in the low32 would probably get mangled before the cast to a pointer type was applied.

You have to escape the quotes

sed -i 's/myTABLE/'$TABLE'/g' my_LKM.c

obviously try first NOT in-place (remove -i )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM