Chinaunix

标题: 小腳本一個,剛寫的 [打印本页]

作者: twf_cc    时间: 2007-06-29 16:36
标题: 小腳本一個,剛寫的
大假未完,天氣差,老婆佔著台式電腦炒股,還未買 Wireless Lan station , 筆記
本不能上網,就那 ruby 書來看,順便試試書中所寫,看到ruby 內建一個method s.reverse
可把字串反過來,反正沒事,用bash 寫一個看看可不可以?我不知有沒有人寫過,但還是重新
寫一個,因為好玩。 :) Linux 好像有一個這樣的命令..忘記了

#! /bin/bash
# reverse the word. Usage: $0 argument(s)
# Jun 29, 2007 [email]twf_cc@yahoo.com.hk[/email]
# public domain

# function

  reverse() {

            # init some staff
              local output=""

            # command line argument
              local word=$1

            # length of input
              local wlength=${#word}

            # split the word,put single char in $output
            # from the last to the first.

              for (( i=$(( wlength - 1 )) ; i>=0  ; i-- ))
                 do
                    local split_word=${word:$i:1}
                    output=${output}${split_word}
                 done

            # print result
              echo $output

            }

  # reverse all arguments
    while [ -n "$1" ]
      do
        reverse "$1"
        shift
      done
作者: Edengundam    时间: 2007-06-29 16:49
echo "try this..." | rev
作者: twf_cc    时间: 2007-06-29 17:12
哈哈,是這個 rev 了,謝!..又重新發明輪子...
作者: ivhb    时间: 2007-06-29 17:29
你这个轮子还是挺有用的呢,我的aix,hp-ux都没有这个rev  :)
作者: twf_cc    时间: 2007-06-29 17:48
多謝使用
作者: cookis    时间: 2007-06-29 19:15
又学到一个 ${wordi:1}
作者: zhanglupanda    时间: 2007-06-29 21:54
厉害呀,就是没看懂!!!
作者: 網中人    时间: 2007-06-29 22:54
我也來一個:
  1. #!/bin/bash

  2. line="$*"
  3. for ((i=${#line};i>0;i--))
  4. do
  5.         echo -n "$*" | cut -c $i
  6. done | tr -d '\n'
  7. echo
复制代码

作者: seeLnd    时间: 2007-06-29 23:40
我也来玩一玩  

  1. echo "ab c d" | sed 's/./&\n/g' | tac | tr -d '\n'
  2. echo "ab c d" | sed 's/./&|/g' | awk -F'|'  '{for(i=NF;i>=1;i--) printf("%s", $i)}'
复制代码

[ 本帖最后由 seeLnd 于 2007-9-28 00:39 编辑 ]




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2