Skip to content

Instantly share code, notes, and snippets.

@jclulow
Created Nov 25, 2011
Embed
What would you like to do?
sed -i handling (illumos)
diff --git a/usr/src/cmd/sed/main.c b/usr/src/cmd/sed/main.c
index 93e14bb..3a3f805 100644
--- a/usr/src/cmd/sed/main.c
+++ b/usr/src/cmd/sed/main.c
@@ -120,7 +120,7 @@ static char *getln(FILE *, size_t *);
int
main(int argc, char *argv[])
{
- int c, fflag;
+ int i, j, c, fflag;
char *temp_arg;
(void) setlocale(LC_ALL, "");
@@ -133,6 +133,23 @@ main(int argc, char *argv[])
fflag = 0;
inplace = NULL;
+ /*
+ * Coalesce |-i ''| into |-i| so that we're compatible with earlier
+ * illumos sed, whilst remaining compatible with GNU sed by using
+ * getopt_long.
+ */
+ for (i = 2; i < argc; i++) {
+ if (strcmp("-i", argv[i - 1]) == 0 && argv[i][0] == '\0') {
+ /* We have: -i '' */
+ for (j = i; j < argc - 1; j++) {
+ /* move the arguments back by one */
+ argv[j] = argv[j + 1];
+ }
+ argv[j] = (char *)NULL;
+ argc--;
+ }
+ }
+
while ((c = getopt_long(argc, argv, "EI::ae:f:i::lnr", lopts, NULL)) !=
-1)
switch (c) {
leftwing@onbld0 tmp $ cc -o tt test.c && ./tt '' -i -i 'awesome' some number -i '' of arguments -i ''
8047b45 -> ''
8047b46 -> '-i'
8047b49 -> '-i'
8047b4c -> 'awesome'
8047b54 -> 'some'
8047b59 -> 'number'
8047b60 -> '-i'
8047b64 -> 'of'
8047b67 -> 'arguments'
8047b71 -> '-i'
0 -> '(null)'
leftwing@onbld0 tmp $ ./tt
0 -> '(null)'
leftwing@onbld0 tmp $ ./tt -i -i
8047b71 -> '-i'
8047b74 -> '-i'
0 -> '(null)'
leftwing@onbld0 tmp $ ./tt -i -i '' -i -i roger -i
8047b61 -> '-i'
8047b64 -> '-i'
8047b68 -> '-i'
8047b6b -> '-i'
8047b6e -> 'roger'
8047b74 -> '-i'
0 -> '(null)'
leftwing@onbld0 tmp $ ./tt -i -i '' -i -i roger -i -j ''
8047b5d -> '-i'
8047b60 -> '-i'
8047b64 -> '-i'
8047b67 -> '-i'
8047b6a -> 'roger'
8047b70 -> '-i'
8047b73 -> '-j'
8047b76 -> ''
0 -> '(null)'
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
int
main(int argc, char *argv[])
{
int i, j;
/* coalesce |-i ''| into |-i| ... */
for (i = 2; i < argc; i++) {
if (strcmp("-i", argv[i - 1]) == 0 && argv[i][0] == '\0') {
/* We have: -i '' */
for (j = i; j < argc - 1; j++) {
/* move arguments back by one */
argv[j] = argv[j + 1];
}
argv[j] = (char *)NULL;
argc--;
}
}
/* print the args */
for (i = 1; i <= argc; i++) {
printf("%p -> '%s'\n", argv[i], argv[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment