954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Shell Script Help

Hi
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

robsammons
Newbie Poster
2 posts since Feb 2005
Reputation Points: 10
Solved Threads: 0
 

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

robsammons
Newbie Poster
2 posts since Feb 2005
Reputation Points: 10
Solved Threads: 0
 

Hello,

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


Wheresed 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
1,$s/$/>>/


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

# Substitute <em>and</em> with <em>&</em>; 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

Stack Overflow
Junior Poster
193 posts since Sep 2004
Reputation Points: 26
Solved Threads: 4
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You