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)
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)
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 fileIf these strings are stored in variables:
var1="abc.out"
You can use parameter subsitution:
var1=${var1%.out}
echo "$var1"
abc
Explanation:
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
$ 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
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
If these are filenames, you can use basename.
$ basename a.out .out
will give you:
a