1

I am trying to insert a /file/path as string at the beginning of the file and have sed returning the code 100, but it is replacing all my files contents:

printf "Message\nMessage\nMessage\n" > test.tex;
sed -i "\@^@{ 1s@^@% Message\n@; q100}" test.tex;
cat test.tex;

Outputs:

% Message
Message

If I try to put 1s on the beginning:

sed -i "\1s@^@{ 1s@^@% Message\n@; q100}" test.tex

It throws the error:

sed: -e expression #1, char 32: unexpected `}'

References:

  1. Return code of sed for no match
  2. How can I pass correctly the parameter `q` with value 100 to my sed expression?

Update

I just noticed it does not make any sense having the return code as 100, so I can just do

sed '1s@^@% Message\n@'

But for curiosity, would this be possible?

Update 2

The correct output would be:

% Message
Message
Message
Message

That is, keep the initial 3 files Message I added to the file.

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

2 Answers2

3

sed's default behavior if it isn't told to do anything else is to echo each line after running any commands that have been specified for it. So when you do sed -i ";" test.tex, it'll run ; on line 1, echo the (unchanged) line, and then move to line 2 and repeat the process. But if you do sed -i "q" test.tex, it makes the (total lack of) changes to line 1, echoes it, then runs the q command and exits immediately without having a chance to echo all the other lines.

That's what's happening in your code. To avoid that issue, you should specify a line range over which the q command will execute. $ is the last line, so:

sed -i "\@^@{ 1s@^@% Message\n@;}; $ {q100}" test.tex;
Ray
  • 1,706
  • 22
  • 30
  • `sed -i "\@^@{ 1s@^@% Message\n@ ;$ q100}"` would probably work too; good explanation +1 – l'L'l Aug 09 '17 at 01:39
1

If you just want to insert a line at the beginning of the file, you could try this

sed -i -e '1i\% Message' -e '$q100' test.tex

The below command instructs sed to insert "%Message" before the first line.

-e '1i\% Message'

The below command instructs sed to quit with return code 100 after printing the last line.

-e '$q100'
Abis
  • 155
  • 8