1

I am having a filename like:2015_q1_cricket_international.txt How can I get the data after underscore(_). my final output should be 2015internationalcricket

3 Answers 3

1

Using awk

Let's create a shell variable with your file name:

$ fname=2015_q1_cricket_international.txt 

Now, let's extract the parts that you want:

$ echo "$fname" | awk -F'[_.]' '{print $1 $4 $3}'
2015internationalcricket

How it works:

  • -F'[_.]' tells awk to split the input anywhere it sees either a _ or a .

  • print $1 $4 $3 tells awk to print the parts that you asked for

Using shell

$ echo "$fname" | { IFS='_.' read a b c d e; echo "$a$d$c"; }
2015internationalcricket

Using sed

$ echo "$fname" | sed -E 's/^([^_.]*)_([^_.]*)_([^_.]*)_([^_.]*).*/\1\4\3/'
2015internationalcricket

Capturing to a shell variable

If we want put the new string in a shell variable, we use command subsitution:

var=$(echo "$fname" | awk -F'[_.]' '{print $1 $4 $3}')

var=$(echo "$fname" | { IFS='_.' read a b c d e; echo "$a$d$c"; })

var=$(echo "$fname" | sed -E 's/^([^_.]*)_([^_.]*)_([^_.]*)_([^_.]*).*/\1\4\3/')

If the shell is bash, we can do this more directly:

IFS='_.' read a b c d e <<<"$fname"
var="$a$d$c"
2
  • Is there any way to take the result to a variable.So that I can make use any where in script.
    – kunaal
    Nov 7, 2015 at 14:49
  • @kunaal Yes. See the updated answer for methods of creating shell variables containing the new string.
    – John1024
    Nov 7, 2015 at 19:49
0

.*_([^_]*)_.* gets «cricket» as \1

0

You can use String.Split('_') and get array of results, or you can use regular expression _[A-Za-z0-9]* which returns all the chars after the underscore which matches three sets.

All the results are returned in an Array.

0

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.