Ubuntu – Copy specific text from a multiple line file and paste it in another file automatically using terminal

bashcommand linetext processing

my question is regarding text processing:

In a list I have the IP addresses and computer names in the following format:

IP address: 192.168.1.25
Computer name: computer7office
IP address: 192.168.1.69
Computer name: computer22office
IP address: 192.168.1.44
Computer name: computer12personal

The output I need:

This computer ip address is xxx.xxx.x.xx and is under the name zzzzzzzzzz

How can I automatically copy the IPs and names from the list to the output file using the command line? Could you please explain your command because it is a pity when I have to copy/paste things that I don't understand.

Best Answer

In sed, assuming your list is in a file called file, you could use:

sed -n '/ss: /N;s/\n//;s/IP address:/This computer ip address is/;s/Computer name:/ and is under the name/p' file
  • -n don't print anything until we ask for it
  • /ss: / find the pattern ss: (to match the lines with IP address:)
  • N read the next line too so we can join them
  • ; separates commands, like in the shell
  • s/old/new/ replace old with new
  • s/\n// delete the newline between the two lines
  • p print the lines we've worked on

When you see what you want, repeat the command adding > newfile at the end of it to write the modified file to newfile

More readably:

sed -n '{
    /ss: /N
    s/\n//
    s/IP address:/This computer ip address is/
    s/Computer name:/ and is under the name/p
}' file | tee newfile

(tee helpfully writes to the newfile and displays the output at the same time)