Keep part of string after hyphen for specific column

Viewed 76

For column 2 in my input files I want to keep the part after the hyphen. I have tried a cut command, but don't know how to apply this to the second column only:

echo TCCCATATGGTCTAGCGGTTAGGATTCCT   1-230823 | cut -d - -f 2
230823

Input:

TCCCATATGGTCTAGCGGTTAGGATTCCT   1-230823
GCATTGGTGGTTCAGTGGTAGAATTCTC    2-172580

Out:

TCCCATATGGTCTAGCGGTTAGGATTCCT   230823
GCATTGGTGGTTCAGTGGTAGAATTCTC    172580
6 Answers

This should help you in awk. Simply substitute everything till - in 2nd column and then print the line(written and tested with shown samples).

awk '{sub(/.*-/,"",$2)} 1' Input_file

2nd solution: In case you want to mention field number into an awk variable;e then try:

awk -v field="2" '{sub(/.*-/,"",$field)} 1' Input_file

Generic solution(which handles multiple field values): In case OP needs to perform substitution in multiple fields which can be defined into an awk variable then please try following.

awk -v field="2,3" '
BEGIN{
  num=split(field,array,",")
  for(i=1;i<=num;i++){ fields[array[i]] }
}
{
  for(i=1;i<=NF;i++){
    if(i in fields){ sub(/.*-/,"",$i) }
  }
}
1' Input_file

You may use this awk:

awk '{sub(/^[^-]*-/, "", $2)} 1' file
TCCCATATGGTCTAGCGGTTAGGATTCCT 230823
GCATTGGTGGTTCAGTGGTAGAATTCTC 172580
$ sed 's/[0-9]*-//' file
TCCCATATGGTCTAGCGGTTAGGATTCCT   230823

You can use the following sed command:

sed -E 's/^([^[:space:]]+[[:blank:]]+)[0-9]+-/\1/' file

See the online sed demo:

s='TCCCATATGGTCTAGCGGTTAGGATTCCT   1-230823
GCATTGGTGGTTCAGTGGTAGAATTCTC    2-172580'
sed -E 's/^([^[:space:]]+[[:blank:]]+)[0-9]+-/\1/' <<< "$s"
# TCCCATATGGTCTAGCGGTTAGGATTCCT   230823
# GCATTGGTGGTTCAGTGGTAGAATTCTC    172580

The POSIX ERE (-E option enables this syntax) regex matches

  • ^ - start of string
  • ([^[:space:]]+[[:blank:]]+) - Group 1 (\1 refers to this group value): one or more non-whitespace chars followed with one or more horizontal whitespace chars
  • [0-9]+- - 1 or more digits and a -.

And with the FS variable, another solution with awk can be:

awk -v FS='[0-9]+-' '{print $1 $2}' input

TCCCATATGGTCTAGCGGTTAGGATTCCT   230823
GCATTGGTGGTTCAGTGGTAGAATTCTC    172580

With multiple delimiters, i.e. hyphen and space, it is better to use awk, e.g.:

<infile awk '{ print $1, $3 }' FS='[- ]+'

Output:

TCCCATATGGTCTAGCGGTTAGGATTCCT 230823
GCATTGGTGGTTCAGTGGTAGAATTCTC 172580
Related