0

I am trying to understand the answer on Return code of sed for no match, but it dos not make any sense the expression sed '/foo/{s/f/b/;q}; /foo/!{q100}'. He could just not create a simple example? Why these so many slashes /, semicolons ; and extra pair of /foo/.

I am trying to replace the tr by foo and make sed have the return code $? of 100 when its succeeds the operation. I tried this code and does not work.

echo "trash"|sed 's/tr/foo/!{q100}'; echo $?

Output is:

sed: -e expression #1, char 10: unknown option to `s'
1

How can I pass correctly the parameter q with value 100 to my sed expression?

Evandro Coan
  • 8,560
  • 11
  • 83
  • 144

1 Answers1

2

Your sed command is wrong; this does the job:

$ echo trash | sed '/tr/{ s/tr/foo/; q100 }'
fooash
$ echo $?
100

What the sed command does:

/tr/ {      # find the tr string, then enter the block
s/tr/foo/;  # replace tr with foo
q100        # exit with 100
}

Unfortunately, sed is well known to be an encrypted language. All the slashes and semicolons need to be decrypted first with eyeballs. I highly recommend you to follow a good and thorough sed tutorial before stepping into the deep water: http://www.grymoire.com/Unix/sed.html

Jason Hu
  • 6,239
  • 1
  • 20
  • 41
  • Thanks, but but why it give error when I replace `/` by `@` as in `echo trash | sed '@tr@{ s@tr@foo@; q100 }'`? If I just call `echo trash | sed '/tr/{ s/tr/foo/; q100 }'` with `/` it does work, but not with `@` – Evandro Coan Aug 08 '17 at 18:50
  • @user this works `echo trash | sed '\@tr@{ s@tr@foo@; q100 }'`. this question is answered in the tutorial i pasted above. – Jason Hu Aug 08 '17 at 18:53