How to delete a substring using shell script

2019-03-25 13:25发布

I have strings called:

abc.out
def.out

How do I delete the substring

.out

In these strings?

What command should I use? (Bourne Shell)

5条回答
Viruses.
2楼-- · 2019-03-25 13:44

If these are filenames, you can use basename.

$ basename a.out .out

will give you:

a
查看更多
Anthone
3楼-- · 2019-03-25 13:54

Multiple ways, a selection:

str=abc.out

Shell:

echo ${str%.*}

Grep:

echo $str | grep -o '^[^\.]*'

Sed:

echo $str | sed -E 's/(.*?)\..*/\1/'

Awk:

echo $str | awk -F. '{print $1}'

Cut:

echo $str | cut -d. -f1

All output:

abc
查看更多
趁早两清
4楼-- · 2019-03-25 14:01

If these strings are stored in a file (let's call it input_file):

# input_file:

abc.out abc.out abc.out
def.out def.out
def.out

You can do:

sed -i 's/\.out//g' input_file

And this will remove any occurrence of the substring .out from that file.

Explanation:

  • sed: invoke the sed tool to edit streams of text
  • -i: use the "in-place" option - this modifies the input file you provide it instead of writing output to stdout
  • 's/\.out//g': Use regular expression to delete .out. the g at the end means delete all occurrences.
  • input_file: specify the input file

If these strings are stored in variables:

var1="abc.out"

You can use parameter subsitution:

var1=${var1%.out}
echo "$var1"

abc

Explanation:

查看更多
\"骚年 ilove
5楼-- · 2019-03-25 14:05
$ foo=abc.def.out
$ echo ${foo%.out}
abc.def

In general, to delete the shortest suffix, use:

$ echo ${foo%.*}
abc.def

To delete the longest suffix, use

$ echo ${foo%%.*}
abc
查看更多
冷血范
6楼-- · 2019-03-25 14:06

I found this worked best because the pattern you want to use can be in a variable:

DATA="abc.out"
pattern=".out"
DATA=${DATA/$pattern/}
echo "DATA=${DATA}"

The result is:

abc

查看更多
登录 后发表回答