Con*_*nfo 6 command-line text-processing
我想使用 sed 或替代解决方案修改文本文件中的每一行
input.txt 包含
line 1
line 2
line 3
...
Run Code Online (Sandbox Code Playgroud)
output.txt 应该添加两个字符串和
<before> line 1 and <after each line>
<before> line 2 and <after each line>
<before> line 3 and <after each line>
...
Run Code Online (Sandbox Code Playgroud)
我可以使用 sed 或其他东西吗?
des*_*ert 10
使用 sed:
sed 's/.*/<before> & and <after each line>/' input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)
s/x/y/ – 用 y 代替 x.* – 走整条线& – 获取匹配的文本其余的只是您要在 前后添加的文本&。
使用 awk:
awk '{print before, $0, after}' before="<before>" after="and <after each line" input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)
这只是打印变量before, $0(当前行)和变量的内容after,以空格分隔。变量在 awk 表达式之后设置。
与perl:
perl -ne 'chomp; print "<before> $_ and <after each line>\n"' in.txt > out.txtRun Code Online (Sandbox Code Playgroud)
这些更改可能有用:
<before>和and <after each line>。> out.txt以将输出发送到您的终端而不是文件。in.txt) 并以交互方式输入输入以进行测试。这个怎么运作:
-p使 Perl 互操作器在每一行上运行(请参阅perldoc perlrun或man perlrun)。-e导致下一个参数是一个 perl 脚本。所以里面的部分' '是 Perl 代码。chomp在每行perl接收的末尾删除行终止符(换行符)。" "带引号的字符串支持插值。$_是读取的行。\n是换行符。perl将in.txt用作输入文件。在>在> out.txt告诉你的shell中的重定向输出。此命令具有相同的效果,因为-p(与 不同-n)自动打印每一行 ( $_):
perl -pe 'chomp; $_ = "<before> $_ and <after each line>\n"' in.txt > out.txtRun Code Online (Sandbox Code Playgroud)
有更多sed类似的使用方法perl。此处显示的方法的优点之一是可读性。
| 归档时间: |
|
| 查看次数: |
4508 次 |
| 最近记录: |