I have a file with multiple lines.

Which the second column is the user_id, but the last seven number are random numbers.

It need to be trimmed off to get the authentic ID.

So what I need is to get the 1st character to the -7 character of the second column of each line.

I've searched substr function of awk, it seems can't handle this job directly.

So, how to cut from the 1st character to -7 character in awk?

  • 4
    what about : susbtr(X,1,length(X)-7) ? – Archemar Mar 5 '15 at 7:58
  • 2
    awk '{$2=substr($2,1, length($2)-7); print $2}' file – jasonwryan Mar 5 '15 at 8:08
  • @jasonwryan,@Archemar that was genius, I didn't consider I can use length func here. Too obstinate in finding some thing similar like [:-7] in python. – Zen Mar 5 '15 at 8:12
  • Why was the question voted down? – Didi Kohen Mar 5 '15 at 8:15
  • 2
    @Archemar, so I guess awk -v id=$TARGET_ID 'substr($2, 1, length($2) -7) == id' will print out every line of the file that its ID is equal to TARGET_ID? – Zen Mar 5 '15 at 8:31
awk '{ print substr($2,1,length($2)-7) }'

If length($2) <= 7, you'll get no output. Should there be a minimum length? If so, you can define a min() function in awk:

awk 'function min(a,b){return a<b?b:a}  ..<rest of code>..'

Assuming that the operations need to be done on the second column (trim last 7 chars):

[whatever command you use to open your file] | awk '{ print $2 }' | rev | cut -c 8- | rev

Here's the breakdown:

awk '{ print $2 }' Gets the second column of the file

rev prepares the string (reverses it). I don't think cut can remove last N characters, so this thing removes first N chars from the reversed string.

cut -c 8- Removes the first 7 characters from the string. (found out by trial and error, needs verification)

rev reverses the processed string. This displays the original string, but without the 7 character thing.

  • 1
    OP asked how to do it in Awk (the presumption being without external tools like rev and cut), and the comments clearly indicate this is possible... – jasonwryan Mar 17 '15 at 17:10

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.