Sed 模式匹配然后追加到行
Sed Pattern Match then Append to Line
下面有一些行,我正在尝试将“检查”附加到以 Apples 开头的行。有人知道我如何在与苹果相同的行上获得“检查”,而不是新的并打印输出吗?我一个人哪儿也去不了。
谢谢
我有:
Grocery store bank and hardware store
Apples Bananas Milk
我想要的:
Grocery store bank and hardware store
Apples Bananas Milk Check
我尝试了什么:
sed -i '/^Apples/a Check' file
我得到的:
Grocery store bank and hardware store
Apples Bananas Milk
Check
使用sed
$ sed '/^Apples/s/.*/& Check/' input_file
Grocery store bank and hardware store
Apples Bananas Milk Check
您可以匹配以 Apples
开头的行,return 它与 &
附加 Check
问题是你a
用a
命令添加了行,见this reference:
The "a" command appends a line after the range or pattern.
你想要的只是一个替代品。但是,您可能还想进行一些调整,这里有一些建议:
sed -i 's/Apples/& Check/g' file # Adds ' Check' after each 'Apples'
sed -i 's/\<Apples\>/& Check/g' file # Only adds ' Check' after 'Apples' as whole word
sed -i -E 's/\<Apples(\s+Check)?\>/& Check/g' file # Adds ' Check' after removing existing ' Check'
请注意这些建议 仅适用于 GNU sed
。 \<
和 `>in GNU sed patterns are word boundaries,
\s+matches one or more whitespaces in GNU
sedPOSIX ERE patterns, and
-E` 启用 POSIX ERE 模式语法。
#!/bin/bash
s='Grocery store bank and hardware store
Apples Bananas Milk'
sed 's/Apples/& Check/g' <<< "$s"
sed 's/\<Apples\>/& Check/g' <<< "$s"
sed -E 's/\<Apples(\s+Check)?\>/& Check/g' <<< "$s"
每种情况下的输出是:
Grocery store bank and hardware store
Apples Check Bananas Milk
这可能适合您 (GNU sed):
sed '/Apples/s/$/ check/' file
如果一行包含 Apples
,则追加字符串 check
。其中 $
表示行尾的锚点(参见 here)。
下面有一些行,我正在尝试将“检查”附加到以 Apples 开头的行。有人知道我如何在与苹果相同的行上获得“检查”,而不是新的并打印输出吗?我一个人哪儿也去不了。
谢谢
我有:
Grocery store bank and hardware store
Apples Bananas Milk
我想要的:
Grocery store bank and hardware store
Apples Bananas Milk Check
我尝试了什么:
sed -i '/^Apples/a Check' file
我得到的:
Grocery store bank and hardware store
Apples Bananas Milk
Check
使用sed
$ sed '/^Apples/s/.*/& Check/' input_file
Grocery store bank and hardware store
Apples Bananas Milk Check
您可以匹配以 Apples
开头的行,return 它与 &
附加 Check
问题是你a
用a
命令添加了行,见this reference:
The "a" command appends a line after the range or pattern.
你想要的只是一个替代品。但是,您可能还想进行一些调整,这里有一些建议:
sed -i 's/Apples/& Check/g' file # Adds ' Check' after each 'Apples'
sed -i 's/\<Apples\>/& Check/g' file # Only adds ' Check' after 'Apples' as whole word
sed -i -E 's/\<Apples(\s+Check)?\>/& Check/g' file # Adds ' Check' after removing existing ' Check'
请注意这些建议 仅适用于 GNU sed
。 \<
和 `>in GNU sed patterns are word boundaries,
\s+matches one or more whitespaces in GNU
sedPOSIX ERE patterns, and
-E` 启用 POSIX ERE 模式语法。
#!/bin/bash
s='Grocery store bank and hardware store
Apples Bananas Milk'
sed 's/Apples/& Check/g' <<< "$s"
sed 's/\<Apples\>/& Check/g' <<< "$s"
sed -E 's/\<Apples(\s+Check)?\>/& Check/g' <<< "$s"
每种情况下的输出是:
Grocery store bank and hardware store
Apples Check Bananas Milk
这可能适合您 (GNU sed):
sed '/Apples/s/$/ check/' file
如果一行包含 Apples
,则追加字符串 check
。其中 $
表示行尾的锚点(参见 here)。