strip the last and first character from a String

To remove the first and last characters from a given string, I like this sed:

sed -e 's/^.//' -e 's/.$//'
#         ^^          ^^
# first char          last char

See an example:

sed -e 's/^.//' -e 's/.$//' <<< "(1 2 3 4 5 6 7)"
1 2 3 4 5 6 7

sed way

$ echo '( 1 2 3 4 5 6 7 )' | sed 's/^.\(.*\).$/\1/'
 1 2 3 4 5 6 7 

awk way

$ echo '( 1 2 3 4 5 6 7 )' | awk '{print substr($0, 2, length($0) - 2)}'
 1 2 3 4 5 6 7 

POSIX sh way

$ var='( 1 2 3 4 5 6 7 )'; var="${var#?}"; var="${var%?}"; echo "$var"
 1 2 3 4 5 6 7 

bash way

$ var='( 1 2 3 4 5 6 7 )'; echo "${var:1: -1}"
 1 2 3 4 5 6 7 

If you use bash then use the bash way.

If not, prefer the posix-sh way. It is faster than loading sed or awk.

Other than that, you may also be doing other text processing, that you can combine with this, so depending on the rest of the script you may benefit using sed or awk in the end.


why doesn't this work? sed '..' s_res.temp > s_res.temp ?

This does not work, as the redirection > will truncate the file before it is read. To solve this you have some choices:

  1. what you really want to do is edit the file. sed is a stream editor not a file editor.
    ed though, is a file editor (the standard one too!). So, use ed:

     $ printf '%s\n' "%s/^.\(.*\).$/\1/" "." "wq" | ed s_res.temp
    
  2. use a temporary file, and then mv it to replace the old one.

     $ sed 's/^.\(.*\).$/\1/' s_res.temp > s_res.temp.temp
     $ mv  s_res.temp.temp  s_res.temp
    
  3. use -i option of sed. This only works with GNU-sed, as -i is not POSIX and GNU-only:

    $ sed -i 's/^.\(.*\).$/\1/' s_res.temp
    
  4. abuse the shell (not recommended really):

     $ (rm test; sed 's/XXX/printf/' > test) < test
    

On Mac OS X (latest version 10.12 - Sierra) bash is stuck to version 3.2.57 which is quite old. One can always install bash using brew and get version 4.x which includes the substitutions needed for the above to work.

There is a collection of bash versions and respective changes, compiled on the bash-hackers wiki

Tags:

Awk

Sed