0

How can I use a script to get rid of the last -xyz.mp4 in a text file list.

Right now I have a long text list that I need changing from

55363642b-b13218-4cb0-8334-546565346-384.mp4
gfdggwg-e1321-4qwe-9ewq-de32155139d8-360.mp4

To

55363642b-b13218-4cb0-8334-546565346
gfdggwg-e1321-4qwe-9ewq-de32155139d8
2
$ sed 's/-[^-]*\.mp4$//' file
55363642b-b13218-4cb0-8334-546565346
gfdggwg-e1321-4qwe-9ewq-de32155139d8

The sed expression s/-[^-]*\.mp4$// is a substitution that matches a dash followed by any number of non-dashes, a dot and the string mp4 (at the very end of the line). The matching text is removed.

To make the change in-place, use the -i flag of sed (but run without first to make sure the result is correct):

sed -i 's/-[^-]*\.mp4$//' file

If these were names of files, I would loop over the actual files instead:

for mp4file in *.mp4; do
    printf 'The truncated name is "%s"\n' "${mp4file%-*.mp4}"
done

The parameter substitution ${mp4file%-*.mp4} would expand to the name of the file with the shortest string matching -*.mp4 removed from the end.

1

sed solution. Looks for a hyphen, followed by 3 characters, followed by .mp4, followed by end of line ($), and replaces with nothing.

Read "file", write shorter names to file "newfile".

sed 's/-...\.mp4$//g' file >newfile

or edit "file" in place

sed -i 's/-...\.mp4$//g' file
0

Using awk:

awk -F- -vOFS=- 'NF{NF-=1};1' file

This will delimit each line with - and remove the last field, then print the remaining fields with the dash re-added.

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.