Substring file name in Unix using sed command

Viewed 86

I want to substring the File name in unix using sed command.

File name : Test_Test1_Test2_10082019_030013.csv.20191008-075740

I want the characters after the 3rd underscore or (all the characters after Test2 ) i need to be printed .

Can this be done using sed command?

I have tried this command

sed 's/^.*_\([^_]*\)$/\1/' <<< 'Test_Test1_Test2_10082019_030013.csv.20191008-075740' 

but this is giving result as 030013.csv.20191008-075740 I need it from 10082019_030013.csv.20191008-075740

Thanks Neha

3 Answers

To remove from the beginning up to including the 3rd underscore you can use

sed 's/^\([^_]*_\)\{3\}//' <<< 'Test_Test1_Test2_10082019_030013.csv.20191008-075740'

This removes the initial part that consists of 3 groups of (any number of non-underscore characters followed by an underscore). The result is

10082019_030013.csv.20191008-075740

If you use GNU sed you can switch it to extended regular expressions and omit the backslashes.

sed -r 's/^([^_]*_){3}//' <<< 'Test_Test1_Test2_10082019_030013.csv.20191008-075740'

Could you please try following.

sed 's/\([^_]*\)_\([^_]*\)_\([^_]*\)_\(.*\)/\4/'  Input_file

Or as per Bodo's nice suggestion:

sed 's/[^_]*_[^_]*_[^_]_\(.*\)/\1/' Input_file

This might work for you (GNU sed):

sed 's/_/\n/3;s/.*\n//;t;s/Test2/\n/;s/.*\n//;t;d' file

Replace the third _ by a newline and then remove everything upto and including the first newline. If this succeeds, bail out and print the result. Otherwise, try the same method with Test2 and if this fails delete the entire line.

Related