windows 如何用sed用双引号将文件中的每一行括起来?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6554066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enclose every line in a file in double quotes with sed?
提问by nw.
This is what I tried: sed -i 's/^.*/"$&"/' myFile.txt
这是我尝试过的: sed -i 's/^.*/"$&"/' myFile.txt
It put a $ at the beginning of every line.
它在每一行的开头放了一个 $。
回答by Karoly Horvath
here it is
这里是
sed 's/\(.*\)/""/g'
回答by jm666
shorter
较短
sed 's/.*/"&"/'
without spaces
没有空格
sed 's/ *\(.*\) *$/""/'
skip empty lines
跳过空行
sed '/^ *$/d;s/.*/"&"/'
回答by anubhava
You almost got it right. Try this slightly modified version:
你几乎猜对了。试试这个稍微修改的版本:
sed 's/^.*$/"&"/g' file.txt
回答by Julian de Bhal
You can also do it without a capture group:
您也可以在没有捕获组的情况下执行此操作:
sed 's/^\|$/"/g'
'^' matches the beginning of the line, and '$' matches the end of the line.
'^' 匹配行首,'$' 匹配行尾。
The |
is an "Alternation", It just means "OR". It needs to be escaped here[1], so in english ^\|$
means "the beginning or the end of the line".
这|
是一个“交替”,它只是意味着“或”。这里需要转义[1],所以在英文中的^\|$
意思是“行的开头或结尾”。
"Replacing" these characters is fine, it just appends text to the beginning at the end, so we can substitute for "
, and add the g
on the end for a global search to match both at once.
“替换”这些字符很好,它只是将文本附加到末尾的开头,因此我们可以替换"
, 并g
在末尾添加以进行全局搜索以同时匹配两者。
[1] Unfortunately, it turns out that | is not part of the POSIX "Basic Regular Expressions" but part of "enhanced" functionality that can be compiled in with the REG_ENHANCED flag, but is not by default on OSX, so you're safer with a proper basic capture group like s/^\(.*\)$/"\1"/
[1] 不幸的是,事实证明 | 不是 POSIX“基本正则表达式”的一部分,而是“增强”功能的一部分,可以用 REG_ENHANCED 标志编译,但在 OSX 上不是默认的,因此使用适当的基本捕获组更安全,例如s/^\(.*\)$/"\1"/
Humble pie for me today.
今天给我谦虚的馅饼。