从字符串中去除最后一个和第一个字符 [英] strip the last and first character from a String

查看:48
本文介绍了从字符串中去除最后一个和第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 awk/sed 从字符串中去除第一个和最后一个字符是否相当容易?

Is fairly easy to strip the first and last character from a string using awk/sed?

说我有这个字符串( 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 方式

$ 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 方式

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方式

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

<小时>

如果您使用 bash 则使用 bash 方式.


If you use bash then use the bash way.

如果没有,更喜欢 posix-sh 方式.它比加载 sedawk 更快.​​

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

除此之外,您还可以进行其他文本处理,您可以将其与此结合,因此根据脚本的其余部分,您可以使用 sedawk到底.

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.

为什么这不起作用?sed '..' s_res.temp >s_res.temp ?

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. 您真正想做的是编辑文件.sed 是一个流编辑器,而不是一个文件编辑器.
    ed 不过,是一个文件编辑器(也是标准的!).所以,使用 ed:

  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

  • 使用临时文件,然后mv替换旧文件.

     $ sed 's/^.\(.*\).$/\1/' s_res.temp > s_res.temp.temp
     $ mv  s_res.temp.temp  s_res.temp
    

  • 使用sed-i选项.这仅适用于 GNU-sed,因为 -inot POSIX 和 GNU-only:

  • 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
    

  • 滥用 shell(真的不推荐):

  • abuse the shell (not recommended really):

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

  • <小时>

    在 Mac OS X(最新版本 10.12 - Sierra)上 bash 被困在相当老的版本 3.2.57 上.始终可以使用 brew 安装 bash 并获取版本 4.x 其中包括上述工作所需的替换.


    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.

    bash-hackers wiki 上编译了一系列 bash 版本和相应的更改.一个>

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

    这篇关于从字符串中去除最后一个和第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆