0

Tool: Git Bash for Windows

Problem: Trying to insert the text "\connect central" at the top of each file in a directory.

Code:

for f in $DIR/*.sql; do
  sed -i "1i \\\connect central" $f
done

This does try to edit inline and insert my text, but three backslashes (like I've read everywhere) doesn't create the single backslash like I'm expected. Instead I get:

enter image description here

I've also tried some variants along the lines of:

for f in $DIR/*.sql; do
  sed -i -e "1i `\\\connect central`" $f
done

but that throws an error of sed: -e expression #1, char 3: expected \ aftera', c',i'`

Daniel
  • 1,364
  • 1
  • 19
  • 34

1 Answers1

3

Use single quotes instead of double quotes. Backslash is an escape character inside double quotes, so you need to double it to pass it through to the sed command literally. It has no special meaning inside single quotes.

sed -i '1i \\\connect central' "$f"

To do it with double quotes (which you might need if there's variable content in the string you're inserting), you have to double all the backslashes:

sed -i "1i \\\\\\connect central" "$f"

For more information, see Difference between single and double quotes in Bash

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • And to explain further, the first backslash is required by the sed `i` command. The backslash which follows must be escaped, as backslash-backslash, so that sed does not treat it specially. Thus, three backslashes are needed by sed. – John1024 Dec 20 '17 at 23:04
  • @John1024 That's already inherent in the command in the question. He knows what the correct `sed` command is, he's just having trouble passing it through from the shell. – Barmar Dec 20 '17 at 23:06
  • Yeah, just couldn't get the right syntax and obviously, the quotes threw me for a loop. Thanks. – Daniel Dec 20 '17 at 23:08
  • @Barmar I wasn't disagreeing. I was just adding. Your answer already has my +1. – John1024 Dec 20 '17 at 23:13
  • @John1024 I understand that, I was just explaining why I didn't think that exposition was necessary for the answer. – Barmar Dec 20 '17 at 23:17