Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash how to append word to end of a line?

Tags:

grep

bash

unix

sed

awk

I have executed a command in bash to retrieve some addresses from a file like this:

grep address file.txt | cut -d'=' -f2 | tr ':' ' '

yields:

xxx.xx.xx.xxx port1
xxx.xx.xx.xxx port2

and I would like to append ' eth0' to each of those output lines and then ideally for loop over the result to call a command with each line. Problem I'm having is getting that extra string in the end to each line. I tried:

| sed -e 's/\(.+)\n/\1 eth0/g'

which didn't work..and then supposing I got it there, if I wrap it in a for loop it won't pass in the full lines since they contain spaces. So how do I go about this?

like image 302
Palace Chan Avatar asked Feb 12 '13 15:02

Palace Chan


People also ask

How do I append to a line in bash?

Using '>>' with 'echo' command appends a line to a file. Another way is to use 'echo,' pipe(|), and 'tee' commands to add content to a file.

Which command append text at the end of the current line?

5. Which command appends text at the end of the current line? Explanation: To append text at end of current line use 'A' command.


2 Answers

I came here looking for the same answer, but none of the above do it as clean as

sed -i 's/address=.*/& eth0/g' file

Search and replace inline with sed for lines begining with address, replace with the same line plus 'eth0'

eg.

sed -i 's/address=.*/& eth0/g' file; cat file
junk line
address=192.168.0.12:80 eth0
address=127.0.0.1:25 eth0
don not match this line
like image 186
Calvin Taylor Avatar answered Sep 17 '22 14:09

Calvin Taylor


You can match $ to append to a line, like:

sed -e 's/$/ eth0/'

EDIT:

To loop over the lines, I'd suggest using a while loop, like:

while read line
do
  # Do your thing with $line
done < <(grep address file.txt | cut -d'=' -f2 | tr ':' ' ' | sed -e 's/$/ eth0')
like image 34
FatalError Avatar answered Sep 18 '22 14:09

FatalError