I am currently working on a project porting a lot of C programs onto a new Linux system. My goal is to automate most of the simple repetitive errors if possible.
Right now I am dealing with a lot of invalid assignments of NULL, which should be '\\0' on that specific line(s). Example:
attribute = NULL;
should be
attribute = '\0';
I have a list of all lines where this error occurs. So now all I need to do is create a script that changes NULL to \\0. This is the line of code I have tried, with different variations:
sed -i "${1}s/NULL/\\0/" ${2}
${1} being the line the error is occuring and ${2} being the filename.
Edit:
Instead of replacing NULL with \\0, it is being replaced as 'NULL'. I need a command that will replace NULL with the characters \\ and 0, not the special character.
$ cat file
attribute = NULL;
$ sed 's/NULL/'\''\\0'\''/' file
attribute = '\0';
You might want to add word boundaries so you don't replace strings with NULL
in them. You must be using GNU sed for that usage of -i
so:
$ cat file
attribute = NULL;
FOONULLBAR
$ sed 's/NULL/'\''\\0'\''/' file
attribute = '\0';
FOO'\0'BAR
$ sed 's/\<NULL\>/'\''\\0'\''/' file
attribute = '\0';
FOONULLBAR
You may want to also consider defining a variable NUL = '\\0'
in a common header and using that in place of NULL
instead of hard-coding \\0
everywhere.
To only do a substitution on a specific line number that's stored in a variable then:
$ lineNr=1; sed "$lineNr"'s/NULL/'\''\\0'\''/' file
attribute = '\0';
FOONULLBAR
$ lineNr=2; sed "$lineNr"'s/NULL/'\''\\0'\''/' file
attribute = NULL;
FOO'\0'BAR
or if you don't mind doubling up on backslashes and know you won't have anything else in your sed command that the shell could interpret/expand (as is true for this specific case):
$ lineNr=1; sed "${lineNr}s/NULL/'\\\\0'/" file
attribute = '\0';
FOONULLBAR
$ lineNr=2; sed "${lineNr}s/NULL/'\\\\0'/" file
attribute = NULL;
FOO'\0'BAR
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.