2

I would manipulate the contents of the second column based on the number of colons it contains. If the second field contains more than one colon then I would require the content before first colon else I would require entire value.

#Input    
1 1131:11854476:4:1$ 0 114476 1 4
5 367504:11862778:4:2$ 0 118628 2 4
3 3:64357_3_2$ 0 18267 2 3 
4 7575:38680372:1$ 0 38372 1 2

# Output
1 1131 0 114476 1 4
5 367504 0 118628 2 4
3 3:64357_3_2$ 0 18267 2 3 
4 7575 0 386372 1 2

I have come across different suggestions to copy a single column after manipulating or processing entire file/string but I would need to retain the remaining columns unprocessed. Could you please give ideas on how to achieve this in a single command (awk/cut one-liners) or multiple commands.

1

1 Answer 1

3

You could split the 2nd field on : and if you get more than 2 pieces (that is, the number of elements in array z) keep only the 1st one:

awk '{n=split($2, z, ":");if (n > 2) $2=z[1]};1' infile

If you wanted to use sub you could do something like:

awk '{sub(/:.*:.*/,"",$2)};1' infile

that is, attempt to replace two colons (or more).

2
  • 1
    I was trying awk '{sub(/:.*/,"",$2)}7' but I was not able to keep 3 row from 2nd column which OP was asking. If I would wanted to modify my awk operation then what it would be ? and I would be thankful if you elaborate your one liner a bit more Commented May 20, 2016 at 11:31
  • @arzyfex - see my edit; is it still unclear ? Commented May 20, 2016 at 11:48

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.