0

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

1
  • 2
    You get a bad substitution because Parameter Expansions works on parameters (variables), e.g. ${param#*/} and ${param::-4}. In ${${newfile#*/}::-4}.gz , ${newfile#*/} is NOT a parameter. Use 2 parameter expansions and don't worry about combining them. Commented Oct 5, 2021 at 5:30

4 Answers 4

2

Perhaps you could use basename, i.e.

name_of_file="something/filename.txt"
newfile=$(basename "${name_of_file%%.*}".gz)
echo "$newfile"
filename.gz
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.