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