How to delete a substring using shell script
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 tostdout
's/\.out//g'
: Use regular expression to delete.out
. theg
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.