0

I need to convert file1 is such way that it has three words in each line, where first is second word from line starting with 'ROBO' and second word is second word from line starting with '1)' and finally third word is fourth word from from line starting with '1)'. See example below...

$cat file1
ROBO lab1 - Topology:
1) 10.195.41.1          10.195.41.255        comment1         
ROBO lab2 - Topology:
1) 10.95.4.1            10.95.4.254          comment2 

to :

lab1 10.195.41.1 comment1
lab2 10.95.4.1 comment2

I ended up with the following:

sed 'N;s/\n/ /' file1| awk '{ if ($6 ~ /^10\./) print $2 " " $6}'

but it breaks when I have something like this:

ROBO lab1 - Topology:
ROBO lab1 - Topology:
1) 10.195.41.1          10.195.41.255        comment1         
ROBO lab2 - Topology:
1) 10.95.4.1 

I need to control that first line starts with 'ROBO' and second starts with '1)' and move down the file if not..until I meet the right pair

  • 1
    Could the comment be several words? – Kusalananda Sep 12 '17 at 19:31
  • 1
    Are the 1)-lines tab separated? – Kusalananda Sep 12 '17 at 19:38
  • Comment could be several words, there is space after '1)' – irom Sep 12 '17 at 19:41
1
$ awk '/^ROBO/ { n = $2 } /^1\)/ { $1 = n; $3 = ""; print }' file1
lab1  10.195.41.1  comment1
lab2  10.95.4.1  comment2

This works as expected, but will contract any consecutive spaces in the comments.

The first part extracts the second word on any ROBO line.

The second part will replace the first input field of any 1) line with the word from the most recent ROBO line and empty the third input field before printing the modified record.

For the second set of example input, this produces

lab1 10.195.41.1  comment1
lab2 10.95.4.1
| improve this answer | |
1

Simply with awk:

"... convert file1 in such way that it has three words in each line ..."

awk '/^ROBO/{ printf "%s ",$2  }/^1\)/{ printf "%s %s\n",$2,$4 }' file1

The output:

lab1 10.195.41.1 comment1
lab2 10.95.4.1 comment2
| improve this answer | |
  • 1
    @Kusalananda, I've intentionally added the OP's condition/citation about three words. So 3 words means 3 words. Otherwise the question should be elaborated – RomanPerekhrest Sep 12 '17 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.