我有以下信息的文件
testing
testing
testing
Run Code Online (Sandbox Code Playgroud)
我想使用sed或任何linux命令在第一个测试单词之前插入一个单词(已测试)
需要输出像
tested
testing
testing
testing
Run Code Online (Sandbox Code Playgroud)
谢谢
mkl*_*nt0 10
提供awk更易于理解的基于替代的替代方案:
awk '!found && /testing/ { print "tested"; found=1 } 1' file
Run Code Online (Sandbox Code Playgroud)
found用于跟踪是否testing已找到第一个实例(变量found,如任何Awk变量,默认为0,即false在布尔上下文中)./testing/因此匹配包含的第一行testing,并处理相关的块:
{ print "tested"; found=1 }打印所需的文本并设置testing已找到第一行的标志1是一种常见的简写{ print },即简单地按原样打印当前输入行.究竟:
Run Code Online (Sandbox Code Playgroud)sed '0,/testing/s/testing/tested\n&/' file
对于包含"测试"的行:
sed '0,/.*testing.*/s/.*testing.*/tested\n&/' file
Run Code Online (Sandbox Code Playgroud)
对于以"测试"开头的行
sed '0,/^testing.*/s/^testing.*/tested\n&/' file
Run Code Online (Sandbox Code Playgroud)
对于以"testing"结尾的行:
sed '0,/.*testing$/s/.*testing$/tested\n&/' file
Run Code Online (Sandbox Code Playgroud)
要使用结果添加"-i"来更新文件的内容,例如:
sed -i '0,/testing/s/testing/tested\n&/' file
Run Code Online (Sandbox Code Playgroud)
这可能适合你(GNU sed):
sed -e '/testing/{itested' -e ':a;n;ba}' file
Run Code Online (Sandbox Code Playgroud)
tested在第一个匹配之前插入testing,然后使用循环读取/打印文件的其余部分.
或者使用GNU特定的:
sed '0,/testing/itested' file
Run Code Online (Sandbox Code Playgroud)