"sed"将反斜杠插入文件 [英] "sed" Insert Backslash to File

查看:503
本文介绍了"sed"将反斜杠插入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

工具:适用于Windows的Git Bash

Tool: Git Bash for Windows

问题:尝试在目录中每个文件的顶部插入文本"\ connect central".

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

代码:

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:

我还尝试了一些类似的变体:

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

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

但是会抛出错误sed: -e expression #1, char 3: expected \ after a',c', i'`

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

推荐答案

使用单引号而不是双引号.反斜杠是双引号内的转义字符,因此您需要将其加倍以将其直接传递给sed命令.在单引号内没有特殊含义.

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"

有关更多信息,请参见 Bash中单引号和双引号之间的差异

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

这篇关于"sed"将反斜杠插入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆