bash Perl:在行首添加字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6847443/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:27:31  来源:igfitidea点击:

Perl: add character to begin of a line

regexperlbash

提问by Adrian

I want to add a " character to the begin of every line in a text file. Is there any simple solution?

我想在文本文件的每一行的开头添加一个 " 字符。有什么简单的解决方案吗?

回答by Aif

perl -p -e 's/^/"/' myfileshould do it!

perl -p -e 's/^/"/' myfile应该做!

$ cat myfile 
0
1
2
3
4
5
6
7
8
9
10
$ perl -p -e 's/^/"/' myfile
"0
"1
"2
"3
"4
"5
"6
"7
"8
"9
"10

回答by glenn Hymanman

Another couple of suggestions:

另外几个建议:

just in the shell:

只是在外壳中:

tmp=$(mktemp)
while read -r line; do printf '"%s\n' "$line"; done < filename > "$tmp" &&
mv "$tmp" filename

ed:

编:

ed describes.sql.bak <<'END'
1,$s/^/"/
w
q
END

回答by TLP

I would consider one of these ways:

我会考虑以下方法之一:

perl -pi.bak -e 's/^/"/' inputfile.txt

Edit file in place, saves a backup in "inputfile.txt.bak".

就地编辑文件,在“inputfile.txt.bak”中保存备份。

perl -pe 's/^/"/' inputfile.txt > outputfile.txt

Use shell redirection to print the output to a new file.

使用 shell 重定向将输出打印到新文件。