I have a text file where the barcode is in column 18. I'm interested in removing the last 16 characters from a TCGA barcode for a long list of samples or alternatively I want to print only the first 12 characters in the string from column 18 to a new column. The characters differ in each line of the file so I can not simply use the sed command to remove characters following a certain character.

For example: TCGA-2E-A9G8-01A-11D-A403-09 needs to be shorted to TCGA-2E-A9G8 and print the shorted ID in a new column

I've seen responses such as: echo "${string:0:-16}" I'm very new to programing so i'm not sure how to automate this for a spreadsheet with over 300,000 lines and directed to a specific column


Using awk:

awk '{print substr($18,1,12)}' input

This will print characters 1-12 of column 18. This assumes that your text file is separated by whitespace. Which it likely isn't.

For CSV:

awk -F, '{print substr($18,1,12)}' input

Based on Steeldriver's comment for adding this output to a new column:

awk '{$(NF+1) = substr($18,1,12)} 1' input > output

Unfortunately this creates a new file. gawk can modify a file in place but your best bet is to create a new file and then remove the old file.

  • Thanks, is there a way to print the trimmed down ID in a new column within the original file?
    – Meghan
    Jun 7 '18 at 14:07
  • I'm not sure what i'm doing wrong. When i do awk '{print substr($18,1,12)}' input>output i'm getting it to print the from the 12 to last column. Not the first 12 characters in column 18.
    – Meghan
    Jun 7 '18 at 14:25
  • Getting it to print the what?
    – jesse_b
    Jun 7 '18 at 14:27
  • its returning data from the 12 to last column
    – Meghan
    Jun 7 '18 at 14:28
  • 2
    Please add the sample data as an edit to your question in a code block so that it's legible.
    – jesse_b
    Jun 7 '18 at 14:50

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.