string manipulation

strings

  • feature

      $ greedy match     : 1#2#3#4 -> 1#2#3
      $ non greedy match : 1#2#3#4 -> 1
      $ last column      : 1#2#3#4 -> 4
              $ last 3 line
              $ first 3 line
              $ all but first 3 lines
              $ all but last 3 lines
    
  • sed

      $ sed -e 's/\(.*\)#.*/\1/'
      $ sed -e 's/\([^#]*\)#.*/\1/'
      $ sed -e 's/.*#//'
    
  • perl

      $ perl -pe 's/(.*)#.*/\1/'
      $ perl -pe 's/(.*?)#.*/\1/'a
      $ perl -pe 's/.*#(.*)/\1/'
      $ perl -lane 'print $F[-1]' (alt. last column)
    
  • ruby

      $ ruby -pe "gsub(/(.*)#.*/,'\1')"
      $ ruby -pe "gsub(/(.*?)#.*/,'\1')"
      $ ruby -pe "gsub(/.*#(.*)/,'\1')"
    
  • awk

      $ awk -F"#" '{{for (i=1; i<NF-1; i++) printf $i "#"} print $(NF-1)}'
      $ awk -F"#" '{print $1}'
      $ awk -F"#" '{print $NF}'
    
  • bash

      $ ???
      $ ???
      $  while IFS="#" read -r -a line; do
          nb=${#line[@]}
          echo ${line[$((nb - 1))]}
         done
    
  • other tools

      $ cut -F# -f1
      $ ???
      $ rev | cut -F# -f1 | rev
    

all pages tagged awk

string manipulation
Posted