开发者

bash/sed/awk: change first alphabet in string to uppercase

Let say I have this list:

39dd809b7a36
d83f42ab46a9
9664e29ac67c
66cf165f7e32
51b9394bc3f0

I want to convert the first occurrence of al开发者_JAVA百科phabet to uppercase, for example

39dd809b7a36 -> 39Dd809b7a36

bash/awk/sed solution should be ok.

Thanks for the help.


GNU sed can do it

printf "%s\n" 39dd809b7a36 d83f42ab46a9 9664e29ac67c 66cf165f7e32 51b9394bc3f0 |
sed 's/[[:alpha:]]/\U&/'

gives

39Dd809b7a36
D83f42ab46a9
9664E29ac67c
66Cf165f7e32
51B9394bc3f0


Pure Bash 4.0+ using parameter substitution:

string=( "39dd809b7a36" "d83f42ab46a9"
         "9664e29ac67c" "66cf165f7e32" "51b9394bc3f0" )

for str in ${string[@]}; do
  # get the leading digits by removing everything
  # starting from the first letter:
  head="${str%%[a-z]*}"
  # and the rest of the string starting with the first letter
  tail="${str:${#head}}"
  # compose result : head + tail with 1. letter to upper case
  result="$head${tail^}"

  echo -e "$str\n$result\n"
done

Result:

39dd809b7a36
39Dd809b7a36

d83f42ab46a9
D83f42ab46a9

9664e29ac67c
9664E29ac67c

66cf165f7e32
66Cf165f7e32

51b9394bc3f0
51B9394bc3f0


I can't think of any clever way to do this with the basic SW tools, but the BFI solution isn't too bad.

In the One True awk(1) or in gawk:

{ n = split($0, a, "")
  for(i = 1; i <= n; ++i) {
    s = a[i]
    t = toupper(s)
    if (s != t) {
      a[i] = t
      break
    }
  }
  r = ""
  for(i = 1; i <= n; ++i) {
    r = r a[i]
  }
  print r
}

It's not too bad in Ruby:

ruby -p -e '$_ = $_.split(/(?=[a-z])/, 2); $_[1].capitalize!'


Here is my solution. It will not allow patterns in form ###.### but can be tweaked as needed.

A=$(cat); B=$(echo $A | sed 's/([a-z])/###\1###/' | sed 's/.###(.)###./\1/' | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/') ; C="echo $A | sed 's/[a-z]/$B/'" ; eval $C

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜