How to delete a substring using shell script

2019-03-25 13:07发布

问题:

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)

回答1:

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:

  • From the above link: "${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var."
  • Note that the "pattern" mentioned here is called globbing, which is different from regular expression in important ways.


回答2:

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


回答3:

$ 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


回答4:

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



回答5:

If these are filenames, you can use basename.

$ basename a.out .out

will give you:

a