2

So I'm trying to parse data into a different format, but the last columns data contains the separator.

If I use:

awk -F: {' print $1 "\t" $2 "\t" $3 '}

and the data is:

ExampleCol1:ExampleCol2:Ex:am:ple:Col3

I only get:

ExampleCol1    ExampleCol2    Ex

How can I grab the rest of the columns after $2? So something like:

print $1 "\t" $2 "\t" $(REST OF COLUMNS)
1

4 Answers 4

0

If I understand your question correctly does this work for you?

sed -e 's/:/\t/1' -e 's/:/\t/1' yourFile

It replaces the first two colons with tabs and prints the rest

With your sample data the output is

ExampleCol1    ExampleCol2    Ex:am:ple:Col3

I'm unsure since in your question you say you get

ExampleCol1:ExampleCol2:Ex

When executing the awk command you provided I get

ExampleCol1    ExampleCol2    Ex
4
  • Hey this should work, I'll run a test now & yeah sorry I miswrote the expected output
    – user358492
    Jun 18, 2019 at 21:40
  • Well it worked to the extent that it replaces the first two seperators ":" as tabs, but if there's data infront of those it outputs to the destination file. Example line - 1:ExampleCol1:ExampleCol2:Ex:am:ple:Col3 Which would output 1 ExampleCol1 Example2 Ex:am:... but I only want the 2 specific cols and rest of col 4 in this case
    – user358492
    Jun 18, 2019 at 21:44
  • 1
    I will mark it as working though, as it works for that format & I can also make slight changes in order to get it working for other formats :), so thank you!
    – user358492
    Jun 18, 2019 at 21:45
  • Happy to help! If it saves you any time I think the modification you want for this other format would be to switch both 1's to 2's Jun 18, 2019 at 21:53
0
_example='ExampleCol1:ExampleCol2:Ex:am:ple:Col3'

awk -F: '{printf $1 "\t" $2 "\t"} {for(i=3;i<=NF;i++) printf $i "\t"} {print ""}' <<<"${_example}"

... looks a little messy but will output...

ExampleCol1 ExampleCol2 Ex  am  ple Col3

... there's likely a more succinct way to express what ya want with awk eg...

awk -F: '{for(i=1;i<=NF;i++) printf $i "\t"} {print ""}' <<<"$_example"

... but the above should get ya a little closer to the desired behavior with awk

Update

Oh looks like ya might have wanted the colons after the second column, if so then...

awk -F: '{printf $1 "\t" $2 "\t"} {for(i=3;i<NF;i++) printf $i ":"} {print $NF}' <<<"$_example"

... might be a little more correct for answering this with awk...

ExampleCol1 ExampleCol2 Ex:am:ple:Col3
0

One way out could be as shown:

 $ awk -vOFS="\t" '{
     sub(/:/, OFS)
     sub(/:/, OFS)
 }1' inp

Or, as another way:

 $ awk '! /:.*:/ || sub(/:/, "\t") && sub(/:/, "\t")' inp
0

Tried with below command and it worked fine

command

 sed "s/:/ /3g" filename| awk -F ":" '{print $1,$2,$3}'| sed "s/ /:/3g"| awk 'OFS="\t" {print $1,$2,$3}'

output

ExampleCol1 ExampleCol2 Ex:am:ple:Col3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .