l..
l..

Reputation: 341

Replace two characters with sed dynamically

I have the following strings

C:/data
D:/backups
C:/Users/Guest/old_data
F:/files/new

How can I replace the first two characters with /cygdrive/LOWERCASE_DRIVE_LETTER?

RESULT

/cygdrive/c/data
/cygdrive/d/backups
/cygdrive/c/Users/Guest/old_data
/cygdrive/f/files/new

Upvotes: 1

Views: 87

Answers (3)

potong
potong

Reputation: 58361

This might work for you (GNU sed):

sed 's/\(.\):/\/cygdrive\/\l\1/' file

Remember by grouping the first character followed by a :. Then insert /cygdrive/ and lowercase the group i.e. the first character.

Upvotes: 2

CWLiu
CWLiu

Reputation: 4043

awk -F':' 'sub(/../,"/cygdrive/"tolower($1))' file

Brief explanation,

  • -F':': set ':' as the field separator.
  • tolower($1): return thee lower case of $1
  • sub(/../,"/cygdrive/"tolower($1)): substitute the first 2 character to "/cygdrive/"tolower($1)

Upvotes: 4

RavinderSingh13
RavinderSingh13

Reputation: 133428

Could you please try following.

awk 'BEGIN{FS=OFS="/"}{sub(/:/,"",$1);$1=tolower($1);print "/cygdrive/" $0}' Input_file

Upvotes: 1

Related Questions