2

I am parsing a file and I use awk to get the first and third field.

This is all good; but in the first field I would like to trim the last 4 char from that string; so far I didn't find a way to do this in awk, and the only way to do so, is to make multiple calls so I save the awk output in 2 variables, and then trim the first string.

Is there a more efficient way to do so? This is what the file look like

abcdefghi.234,12345,xyz
riosadsef.543,19432,eis
baifafsag.342,01934,eod

This is what I run in the loop

echo $output | awk -F, "{print $1, $3}"

This will print the line correctly, but then I want to trim $1, removing the last 4 chars

  • Your code with $1 inside doublequotes " should not work as described; shell needs singlequotes ' to include actual $ in an argument. IF as per your example the unwanted characters always begin with . and . is not used elsewhere, you could treat both as field delimiters: awk -F'[.,]' '{print $1,$4}' – dave_thompson_085 Nov 4 '16 at 7:51
2

One method is to use awk's substr function. For example, starting with this input:

$ cat input
abcdefghi.234,12345,xyz
riosadsef.543,19432,eis
baifafsag.342,01934,eod

We can print columns one and three, omitting the last four characters of column one with:

$ awk -F, '{print substr($1, 1, length($1)-4), $3}' input
abcdefghi xyz
riosadsef eis
baifafsag eod
| improve this answer | |
  • Awesome; I felt like there was a better way, instead than write 3 more lines and do the trimming on the variable value. Thanks! – rataplan Nov 4 '16 at 5:48

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.