user1536726
user1536726

Reputation:

How to extract string in shell script

I have file names like Tarun_Verma_25_02_2016_10_00_10.csv. How can I extract the string like 25_02_2016_10_00_10 from it in shell script?

It is not confirmed that how many numeric parts there would be after "firstName"_"lastName"

A one-line solution would be preferred.

Upvotes: 0

Views: 75

Answers (3)

karakfa
karakfa

Reputation: 67467

with sed

$ echo Tarun_Verma_25_02_2016_10_00_10.csv | sed -r 's/[^0-9]*([0-9][^.]*)\..*/\1/'

25_02_2016_10_00_10

extract everything between the first digit and dot.

Upvotes: 2

JNevill
JNevill

Reputation: 50019

If you want some control over which parts you pick out (assuming the format is always like <firstname>_<lastname>_<day>_<month>_<year>_<hour>_<minute>_<second>.csv) awk would be pretty handy

 echo "Tarun_Verma_25_02_2016_10_00_10.csv" | awk -F"[_.]" 'BEGIN{OFS="_"}{print $3,$4,$5,$6,$7,$8}'

Here awk splits by both underscore and period, sets the Output Field Seperator to an underscore, and then prints the parts of the file name that you are interested in.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295316

ksh93 supports the syntax bash calls extglobs out-of-the-box. Thus, in ksh93, you can do the following:

f='Tarun_Verma_25_02_2016_10_00_10.csv'
f=${f##+([![:digit:]])} # trim everything before the first digit
f=${f%%+([![:digit:]])} # trim everything after the last digit
echo "$f"

To do the same in bash, you'll want to run the following command first

shopt -s extglob

Since this uses shell-native string manipulation, it runs much more quickly than invoking an external command (sed, awk, etc) when processing only a single line of input. (When using ksh93 rather than bash, it's quite speedy even for large inputs).

Upvotes: 0

Related Questions