LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Need help appending text to lines in a file using vi editor (https://www.linuxquestions.org/questions/linux-newbie-8/need-help-appending-text-to-lines-in-a-file-using-vi-editor-680336/)

tmbrwolf53 10-31-2008 02:32 PM

Need help appending text to lines in a file using vi editor
 
I'm somewhat new to Linux and very new to the vi editor. Here is my issue:
I have a file that I want to append text to the end of each line within the file. The text to be added is the same.
How do I setup a command to mass append the text to each line? I have played with substitution but have not been able to append data at the end.

Here is an example. I have a file that looks like this:

du -sh us1234
du -sh us5678
du -sh us9abc
du -sh usefgh
du -sh usijgl
du -sh usmnop
du -sh usqrst

I want to append the following to each line:
" >> /tmp/output.txt"
So each line will look like:

du -sh us1234 >> /tmp/output.txt
du -sh us5678 >> /tmp/output.txt
du -sh us9abc >> /tmp/output.txt
du -sh usefgh >> /tmp/output.txt
du -sh usijgl >> /tmp/output.txt
du -sh usmnop >> /tmp/output.txt
du -sh usqrst >> /tmp/output.txt

How do I accomplish this with a single command?

paulsm4 10-31-2008 02:38 PM

Before:
Quote:

du -sh us1234
du -sh us5678
du -sh us9abc
du -sh usefgh
du -sh usijgl
du -sh usmnop
du -sh usqrst
Command:
Code:

:1,$s/$/ >> \/tmp\/output\.txt/
After:
Quote:

du -sh us1234 >> /tmp/output.txt
du -sh us5678 >> /tmp/output.txt
du -sh us9abc >> /tmp/output.txt
du -sh usefgh >> /tmp/output.txt
du -sh usijgl >> /tmp/output.txt
du -sh usmnop >> /tmp/output.txt
du -sh usqrst >> /tmp/output.txt
Let's break it down:
1. <Esc>, : Go into command mode
2. 1,$ Execute this command on every line between 1 and End of file ("$")
3. s/$/ >> \/tmp\/output\.txt/ The command is "substitute" ("s/X/Y/")
4. /$/ >> \/tmp\/output\.txt/ This means:
a) substitute "end of line" ($)
b) for " >> /tmp/output.txt"
c) Escape the "/" and "." metacharacter (using "\")

'Hope that helps .. PSM

Tinkster 10-31-2008 02:50 PM

Or give vi a miss and use sed ;}

Code:

sed -i 's@$@>> /tmp/output.txt@' file
Cheers,
Tink

tmbrwolf53 10-31-2008 03:25 PM

Thank you paulsm4 and tinkster. Both worked


All times are GMT -5. The time now is 12:01 PM.