Sed append text to end of line if line contains specific text? How can this be done?
Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Sed append text to end of line if line contains specific text? How can this be done?
Hi All,
I'm trying to get sed to add some text to the end of a line if that line contains a specific piece of text.
Quite simple i have a script...
echo blah
df -h
echo blah1
cd /usr/share
echo blah2
ls -al
echo blah1
And i want to use sed (i think is probably right for the job) to add text to the end of all the lines that are 'echo'
I've seen that you can :-
sed 's/$/text/' filename
But that appends to every single line i want to do something like
sed 's|echo*$|>> /var/log/output_to_log.txt|' filename
As you can see i want all the echo's to send out to a log, in the script i've already created but at the moment the echo's just send to stout, and i could run the script with filename 2>&1 /var/log/output_to_log.txt, but i'm trying to do it this other way.
Any ideas?
Cheers,
MJ
Last edited by helptonewbie; 11-19-2008 at 11:28 AM.
#!/bin/bash -
# @(#) s1 Demonstrate append text to end of selected lines.
echo
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version "=o" $(_eat $0 $1) sed
set -o nounset
echo
echo " Results:"
cat <<EOF |
echo blah
df -h
echo blah1
cd /usr/share
echo blah2
ls -al
echo blah1
EOF
sed '/^echo/s|$| >> /var/log/output_to_log.txt|'
exit 0
Producing:
Code:
% ./s1
(Versions displayed with local utility "version")
Linux 2.6.11-x1
GNU bash 2.05b.0
GNU sed version 4.1.2
Results:
echo blah >> /var/log/output_to_log.txt
df -h
echo blah1 >> /var/log/output_to_log.txt
cd /usr/share
echo blah2 >> /var/log/output_to_log.txt
ls -al
echo blah1 >> /var/log/output_to_log.txt
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.