Home > front end >  Remove and replace characters from string with one command
Remove and replace characters from string with one command

Time:10-05

I need to remove characters from string and then replace other characters. This is the initial string:

something/filename.txt

I need to remove the directory "something" (can be any other name) and replace .txt with .gz The following 2 commmands work perfect:

newfile=${newfile#*/}
newfile=${newfile::-4}.gz

So the output will be: filename.gz Is there a way to do it in a single command? Something like:

${${$newfile#*/}::-4}.gz 

With the above command I get: bad substitution error.

Thank you Lucas

CodePudding user response:

Perhaps you could use basename, i.e.

name_of_file="something/filename.txt"
newfile=$(basename "${name_of_file%%.*}".gz)
echo "$newfile"
filename.gz

CodePudding user response:

new_file=something/filename.txt
new_file="${new_file#*/}"
new_file="${new_file%.*}.gz"

Is there a way to do it in a single command?

echo something/filename.txt | sed 's|.*/||;s|\..*$|.gz|'

CodePudding user response:

Since your question is tagged bash, you can use Bash builtin regex to capture the group you need like this:

#!/usr/bin/env bash

filepath=something/filename.txt

# Regex group capture basename without dot suffix || exit err if not matching
[[ $filepath =~ .*/(.*)\.[^.]* ]] || exit

# Compose new file name from Regex captured group and new .gz extension
newfilename=${BASH_REMATCH[1]}.gz

# debug dump variables
declare -p filepath newfilename

CodePudding user response:

A combination of cut and sed can help as below

oldfile='somethingelse/filename.txt'
newfile=`echo $oldfile | cut -d "/" -f2 |sed 's!.txt!.gz!g'`
echo $newfile

This displays filename.gz

EDIT In case there are subdirectories and you want only file name

oldfile='somethingelse/other/filename.txt'
newfile=`echo $oldfile | rev| cut -d "/" -f1 |rev |sed 's!.txt!.gz!g'`
echo $newfile

The cut command gets the last field delimited by "/" .

Happy to be corrected and learn.

  •  Tags:  
  • bash
  • Related