Sed - delete all characters before the dash

I have a list of file names for which I want to delete all characters before the first instance. Therefore, the names shown below in the Before: list are displayed 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 play with sed for several hours to no avail.

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

+4
source share
8 answers

With awk you can:

 awk 'BEGIN{FS=OFS="- "} NF>1{$1="";sub(/^- */, "")}'1 inFIle 

Live Demo: http://ideone.com/2tBU4v

+2
source

Like this.

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

Many regex mechanisms allow *? for a non greedy search, but sed doesn't.

EDIT: this will not change the William-Kent example, the inline hyphen will prevent a match.

(In addition, Perl sends a very handy rename script to batch rename files using regular expressions, but not every distribution installs it.)

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

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

+4
source

The simplest approach is used too grep :

 $ grep -Po ' - \K.*' file Welcome Home.txt One Upon - A Time.txt Prince & The Frog.txt 
+3
source

It seems to me that gawk might be easier for this job.

using FPAT can simplify the problem:

 awk -v FPAT="- .*$" 'sub(/^- /,"",$1)' file 

with your data:

 kent$ echo "Adam James - Welcome Home.txt Mike & Harry - One Upon - A Time.txt William-Kent - Prince & The Frog.txt"|awk -v FPAT="- .*$" 'sub(/^- /,"",$1)' Welcome Home.txt One Upon - A Time.txt Prince & The Frog.txt 
+1
source

In pure Bash (no additional child processes are generated):

 list=('Adam James - Welcome Home.txt' 'Mike & Harry - One Upon - A Time.txt') for str in "${list[@]}"; do echo ${str#*-}; done 

Print

 Welcome Home.txt One Upon - A Time.txt 
+1
source

This can be done in simple POSIX sh, without bash functions:

 $ cat the_file_names Adam James - Welcome Home.txt Mike & Harry - One Upon - A Time.txt William-Kent - Prince & The Frog.txt $ { while read FN; do echo ${FN#* - }; done; } < /tmp/the_file_names Welcome Home.txt One Upon - A Time.txt Prince & The Frog.txt $ 
+1
source

This may work for you (GNU sed):

  sed 's/ - /\n/;s/.*\n//' file 
+1
source

All Articles