1

Using awk, I'm trying to print the fourth field of an input line ($4) also at the begining of the line.

I have tried the following code, but it prints the string above the line:

awk -F"[--]" '{print $4 ;print$0}' file 

The string is random so I can't use the string name.

The input like looks as follows:

/example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 

With the code above I get:

320 /example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 

I need the output to look like:

320/example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 

Thanks for help!

2 Answers 2

5

Separate print statements will print separate records (lines) by default. Use a single print, concatenating $4 and $0:

% awk -F- '{print $4 $0}' input 320/example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 
0
1

If some of your dashes at the start of the lines disappear, it will be difficult to pick out the string to prepend to each line by its field number as it may not always be field 4, as in

$ cat file /example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 /example.origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 /example.origin.live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 

Instead, the following picks out the second --delimited word after the : on each line:

$ sed 's/^\([^:]*:[^-]*-\([^-]*\)\)/\2\1/' file 320/example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 320/example.origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 320/example.origin.live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 

Or, arguably more readable with awk:

$ awk -F ':' '{ split($2,a,"-"); print a[2] $0 }' file 320/example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 320/example.origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 320/example.origin.live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 

That assumes that the line is basically two :-delimited fields, then splits the second of these up on - and uses the second of the resulting fields for the output.

If the end bit of each line has static formatting, then you could obviously count fields from the end instead of from the start and use awk like so:

$ awk -F '-' '{ print $(NF - 5) $0 }' file 320/example-origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 320/example.origin-live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 320/example.origin.live/ngrp:tennis-320-fd1d9b92-69e2-446c-a3e6-45b33a55efc9 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.