简体   繁体   English

Bash从字符串中剪切第一个和/或最后一个字符,但前提是它是某个特定字符

[英]Bash shave a first and/or last character from string, but only if it is a certain character

In bash I need to shave a first and/or last character from string, but only if it is a certain character. 在bash中,我需要从字符串中删除第一个和/或最后一个字符,但前提是它只是某个字符。

If I have | 如果我有| I need 我需要

/foo/bar/hah/   =>   foo/bar/hah

foo/bar/hah     =>   foo/bar/hah

You can downvote me for not listing everything I've tried. 你可以用我没有列出我尝试过的所有东西。 But the fact is I've tried at least 35 differents sed strings and bash character stuff, many of which was from stack overflow. 但事实是我已经尝试了至少35个不同的sed字符串和bash字符的东西,其中许多是来自堆栈溢出。 I simply cannot get this to happen. 我根本无法让这件事发生。

In pure : 纯粹的

$ var=/foo/bar/hah/
$ var=${var%/}
$ echo ${var#/}
foo/bar/hah
$ 

Check bash parameter expansion 检查bash参数扩展

or with : 或者用

$ sed -r 's@(^/|/$)@@g' file

what's the problem with the simple one? 简单的问题是什么?

sed "s/^\///;s/\/$//"

Output is 输出是

foo/bar/hah
foo/bar/hah

这个怎么样:

echo "$x" | sed -e 's:^/::' -e 's:/$::'

Further to @sputnick's answer and from this answer , here's a function that would do it: 继@ sputnick的答案和答案之后 ,这里有一个函数可以做到:

STR="/foo/bar/etc/";
STRB="foo/bar/etc";

function trimslashes {
    STR="$1"
    STR=${STR#"/"}
    STR=${STR%"/"}
    echo "$STR"
}

trimslashes $STR
trimslashes $STRB

# foo/bar/etc
# foo/bar/etc
 echo '/foo/bar/hah/' | sed 's#^/##' | sed 's#/$##'

assuming the / character is the only one you're trying to remove, then sed -E 's_^[/](.*)_\\1_' should do the job: 假设/字符是你要删除的唯一一个,那么sed -E 's_^[/](.*)_\\1_'应该完成这项工作:

$ echo "$var1"; echo "$var2"
/foo/bar/hah
foo/bar/hah


$ echo "$var1" | sed -E 's_^[/](.*)_\1_'
foo/bar/hah


$ echo "$var2" | sed -E 's_^[/](.*)_\1_'
foo/bar/hah

if you also need to replace other characters at the start of the line, add it to the [/] class. 如果您还需要在行的开头替换其他字符,请将其添加到[/]类。 for example, if you need to replace / or - , it would be sed -E 's_^[/-](.*)_\\1_' 例如,如果你需要替换/- ,它将是sed -E 's_^[/-](.*)_\\1_'

Here is an awk version: 这是一个awk版本:

echo "/foo/bar/hah/" | awk '{gsub(/^\/|\/$/,"")}1'
foo/bar/hah

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM