Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - delete all characters before dash

Tags:

bash

sed

awk

I have list of filenames for which I want to remove all character before the first instance of -. So the names below in the Before: list appears as those in the After: list.

Before:
Adam James - Welcome Home.txt
Mike & Harry - One Upon - A Time.txt
William-Kent - Prince & The Frog.txt

After:
Welcome Home.txt
One Upon - A Time.txt
Prince & The Frog.txt

I've been playing around with sed for hours with no avail.

I found that sed 's/ - .*//' removes all characters after the first instance of - but I cannot find the same for before.

like image 287
scripting_newbie Avatar asked Nov 29 '22 13:11

scripting_newbie


2 Answers

$ awk '{print substr($0,index($0," - ")+3)}' file
Welcome Home.txt
One Upon - A Time.txt
Prince & The Frog.txt

i.e. just print from the end of the first occurrence of " - " to the end of the line.

like image 197
Ed Morton Avatar answered Jan 17 '23 23:01

Ed Morton


Like this.

sed 's/^[^-]* - //'

Many regular expression engines allow *? for a non-greedy search, but sed doesn't.

EDIT: This won't change the William-Kent example, the embedded hyphen prevents a match.

(Also, Perl ships a very handy rename script to batch-rename files using regular expressions, but not every distribution installs it.)

like image 22
pdw Avatar answered Jan 17 '23 22:01

pdw