I am trying to write a pipeline which updates the content
of a file by replacing all the mathches of the word 'and'
with the symbol '&' and replaces the end of each line with
my name. I have tried using sed and can replace the and's but can't put my name at the end of each line. Please help.

Thanks Rob

I have managed to add my name now but it only add it to the end of the paragraph not the end of the line. Is there anyway to correct this?. Here is my code:

sed -i 's/and/\&/g;s/$/'Rob Sammons'/g' ./Coursework.txt && echo YES || echo NO


You're on the right path, though your syntax is a bit off. We know that sed substitutes text using the s command. Suppose you wanted to change all occurrences of "Unix" in the text to "UNIX":

# Substitute Unix with UNIX
sed 's/Unix/UNIX' intro

Where sed is the program, s is the substitute command in sed, /Unix/UNIX is the command, and intro is the file.

The dollar sign $ is used to match the end of the line. The following example will add >> to the end of each line found in the file specified:

# Append >> at the end of each line

With all of this in mind, we can create a simple script to accomplish your task:

# Substitute [i]and[/i] with [i]&[/i]; and append "Rob Sammons" to the end of each line
sed -i 's/and/\&/g;1,$s/$/"Rob Sammons"/' Coursework.txt

Output before running command:

Hello, this is a test for sed and so on.
Let's hope this works.

Output after script executed:

Hello, this is a test for sed & so on."Rob Sammons"
Let's hope this works."Rob Sammons"

To clarify:

sed — Is the program.
-i — Is a sed option that can edit files in place (makes backup if extension supplied)
s — Is the substitute command in sed
/and/\&/g — Substitutes all occurences of and to &
1,$s/$/"Rob Sammons"/ — Appends "Rob Sammons" at the end of each line.
Coursework.txt — Is the input file.

- Stack Overflow

This article has been dead for over six months. Start a new discussion instead.