0

I have a string which is input string ./y1563/y1563.xls want to convert it to a string output y1563/y1563.txt.

5
  • have you already tried a simple substitution? Nov 12, 2019 at 8:26
  • NAME=./y1563/y1563.xls VAR=echo $NAME |sed -n 's/.xls//p' I tried this.. Nov 12, 2019 at 8:27
  • 1
    please add some context to your question. I have the feeling that it is an XY-Problem
    – pLumo
    Nov 12, 2019 at 8:32
  • use ${VAR%.*}.txt
    – pLumo
    Nov 12, 2019 at 8:33
  • I have file location which is ./y1563/y1563.xls and I want to create another file in $PWD/summary/y1563/y1563.txt. In order to do this, I need to get the "y1563/y1563.txt" from input string or current file location(./y1563/y1563.xls) Nov 12, 2019 at 8:41

1 Answer 1

1

You don't generally use sed to modify a string that you have (according to your comment) in a shell variable. At least not if all you want to do is to remove and/or replace the suffix of the string.

Instead,

NAME=./y1563/y1563.xls
NAME=${NAME%.xls}.txt    # remove .xls suffix, append .txt suffix
NAME=${NAME#./}          # remove ./ prefix (this may not be needed)

These (${variable%pattern} and ${variable#pattern}) are standard variable substitutions that removes suffix and prefix strings from a variable's value.

This would also work properly even if the $NAME value contains embedded newline characters. Newlines are allowed in filenames, but since sed is a line-oriented editor, it would not handle such input correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.