Sed Pattern Match then Append to Line

Viewed 644

I have some lines down below and I'm trying to append "Check" to the line that starts with Apples. Does someone know how I can get "Check" on the same line as Apples, not a new one and print the output? I wasn't getting anywhere on my own.

Thanks

What I have:

Grocery store bank and hardware store
Apples Bananas Milk

What I want:

Grocery store bank and hardware store
Apples Bananas Milk Check

What I tried:

sed -i '/^Apples/a Check' file

What I got:

Grocery store bank and hardware store
Apples Bananas Milk
Check
3 Answers

This might work for you (GNU sed):

sed '/Apples/s/$/ check/' file

If a line contains Apples append the string check. Where $ represents an anchor that is the end of the line (see here).

Using sed

$ sed '/^Apples/s/.*/& Check/' input_file
Grocery store bank and hardware store
Apples Bananas Milk Check

You can match lines that begin with Apples, return it with & appending Check

The problem is that you append the line with a command, see this reference:

The "a" command appends a line after the range or pattern.

What you want is a mere substitution. However, there may be some more tweaks you would like to implement, here are some suggestions:

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'

Note these suggestions are for GNU sed only. \< and `>in GNU sed patterns are word boundaries,\s+matches one or more whitespaces in GNUsedPOSIX ERE patterns, and -E` enables the POSIX ERE pattern syntax.

See the online demo:

#!/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"

Output in each case is:

Grocery store bank and hardware store
Apples Check Bananas Milk
Related