简体   繁体   English

Bash 脚本将单词括在单引号中

[英]Bash script to enclose words in single quotes

I'm trying to write a bash script to enclose words contained in a file with single quotes.我正在尝试编写一个 bash 脚本来用单引号将文件中包含的单词括起来。

Word - Hello089词 - 你好089

Result - 'Hello089',结果 - 'Hello089',

I tried the following regex but it doesn't work.我尝试了以下正则表达式,但它不起作用。 This works in Notepad++ with find and replace.这适用于带有查找和替换的 Notepad++。 I'm not sure how to tweak it to make it work in bash scripting.我不确定如何对其进行调整以使其在 bash 脚本中工作。

sed "s/(.+)/'$1',/g" file.txt > result.txt

Replacement backreferences (also called placeholders) are defined with \n syntax, not $n (this is perl-like backreference syntax).替换反向引用(也称为占位符)是用\n语法定义的,而不是$n (这是类似于 perl 的反向引用语法)。

Note you do not need groups here, though, since you want to wrap the whole lines with single quotation marks.但是请注意,这里不需要组,因为您想用单引号将整行括起来。 This is also why you do not need the g flags, they are only necessary when you plan to find multiple matches on the same line , input string.这也是您不需要g标志的原因,它们仅在您计划在同一行查找多个匹配项时才需要,输入字符串。

You can use the following POSIX BRE and ERE (the one with -E ) solutions:您可以使用以下 POSIX BRE 和 ERE(带有-E的那个)解决方案:

sed "s/..*/'&',/" file.txt > result.txt
sed  -E "s/.+/'&',/" file.txt > result.txt

In the POSIX BRE (first) solution, ..* matches any char and then any 0 or more chars (thus emulating .+ common PCRE pattern).在 POSIX BRE(第一个)解决方案中, ..*匹配任何字符,然后匹配任何 0 个或多个字符(因此模拟.+常见的 PCRE 模式)。 The POSIX ERE (second) solution uses .+ pattern to do the same. POSIX ERE(第二个)解决方案使用.+模式来做同样的事情。 The & in the right-hand side is used to insert the whole match (aka \0 ).右侧的&用于插入整个匹配项(又名\0 )。 Certainly, you may enclose the whole match with capturing parentheses and then use \1 , but that is redundant:当然,您可以用捕获括号将整个匹配括起来,然后使用\1 ,但这是多余的:

sed "s/\(..*\)/'\1',/" file.txt > result.txt
sed  -E "s/(.+)/'\1',/" file.txt > result.txt

See the escaping, capturing parentheses in POSIX BRE must be escaped.请参阅 escaping,必须转义 POSIX BRE 中的捕获括号。

See the online sed demo .请参阅在线sed演示

s="Hello089";
sed "s/..*/'&',/" <<< "$s"
# => 'Hello089',
sed -E "s/.+/'&',/" <<< "$s"
# => 'Hello089',

$1 is expanded by the shell before sed sees it, but it's the wrong back reference anyway. $1sed看到它之前由 shell 扩展,但无论如何它都是错误的反向引用。 You need \1 .你需要\1 You also need to escape the parentheses that define the capture group.您还需要转义定义捕获组的括号。 Because the sed script is enclosed in double quotes, you'll need to escape all the backslashes.因为sed脚本用双引号括起来,所以您需要转义所有反斜杠。

$ echo "Hello089" | sed "s/\\(.*\\)/'\1',/g"
'Hello089',

(I don't recall if there is a way to specify single quotes using an ASCII code instead of a literal ' , which would allow you to use single quotes around the script.) (我不记得是否有一种方法可以使用 ASCII 代码而不是文字来指定单引号' ,这将允许您在脚本周围使用单引号。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM