0

I have filenames with MP4 extensions that do not end with _special.MP4:

mylist=$(ls | grep -v "_special.MP4")

Then, I'd like to remove the .MP4 extension from this subsequent list.

echo $mylist | sed -e 's/\.MP4$//'

only remove the last .MP4 occurrence, how can I get them all?

3
  • It's not a good idea to parse the output of ls and sed can't operate on filenames. It can only operate on the contents of files or standard output. You'll want to use a utility like rename. – Nasir Riley Aug 2 '20 at 4:33
  • Please note: Why not parse ls? – Cyrus Aug 2 '20 at 6:39
  • Quoting "$mylist" may help. – guest Aug 2 '20 at 8:10
2

Let's say I have these files that end in .MP4:

.
├── 1.MP4
├── 2.MP4
└── 3_special.MP4

If I understand correctly, you want the names of the non-special files, minus the .MP4 extension.

First of all, I would use find instead of ls because it's easier to control and easier to parse the output. Either way, you'll end up with a list files separated by newline characters:

$ find . -name '*.MP4' -not -name '*_special.MP4'
./1.MP4
./2.MP4

Your sed command will work as is because the $ in the pattern binds to the end of each line:

$ find . -name '*.MP4' -not -name '*_special.MP4' | sed -e 's/\.MP4$//'
./1
./2

The basename command will actually do most of this for you; you don't even need sed! The primary use of basename is to remove the directory from the front of a path, but it also supports removing suffixes.

SYNOPSIS

basename string [suffix]

basename only accepts a single word in the "string" position, so you need to use xargs to run it once for each file.

$ find . -name '*.MP4' -not -name '*_special.MP4' | xargs -I -name- basename -name- .MP4
1
2
2

With bash:

shopt -s extglob            # enable extglob
mylist=( !(*_special.MP4) ) # fill array but without files with suffix _special.MP4
echo "${mylist[@]%.MP4}"    # remove suffix .MP4

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.