How to delete a substring using shell script How to delete a substring using shell script shell shell

How to delete a substring using shell script


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}'

-F. means split the string by . and $1 means the first column.

Cut:

echo $str | cut -d. -f1

All output:

abc


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

# input_file:abc.out abc.out abc.outdef.out def.outdef.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:


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