1

I have a string abc_d_e75_f10_xyz_l_11 I want to split it so that I want to construct a string of an existing directory from this string to cd to it.

So in this example abc_d_e75_f10_xyz_l_11 I want to split using the _ character where I want to write this command cd /home/userA/abc/d_e75_f10 and neglect the rest of the string.

3 Answers 3

2

You can do:

echo "abc_d_e75_f10_xyz_l_11" | sed 's/_/\//' | cut -d "_" -f1-3

This will replace the first _ with / as well as trim the string.

Output:

abc/d_e75_f10

3
  • 1
    what does this do -f1-3?
    – Tak
    Sep 28, 2014 at 22:29
  • 1
    -f1-3 Means select only fields 1 to 3. d is field 1. e75 is field 2, etc. Sep 28, 2014 at 22:32
  • You could do this in a single sed command. Oct 19, 2014 at 4:20
0

You can use the bash shell's built-in string manipulation capabilities e.g.

$ var="abc_d_e75_f10_xyz_l_11"
$ echo "/home/userA/${var/_//}"
/home/userA/abc/d_e75_f10_xyz_l_11
1
  • 1
    But he wants to neglect everything after the fourth field f10.
    – Alaa Ali
    Sep 28, 2014 at 22:20
0

You want sed.

sed is a tool for performing search and replace operations on text.

In this case it seems like you want to replace the first occurrence of _ with /.

This will do that: echo "abc_d_e75_f10_xyz_l_11" | sed "s/_/\//"

It looks wierd with the slashes but the idea is "s/search/replace/". And / has to be escaped.

3
  • its giving this error sed: -e expression #1, char 6: unknown option to s'` and I want to neglect everything after the fourth field f10.
    – Tak
    Sep 28, 2014 at 22:24
  • Sorry forgot the quotes, updated my answer
    – Dan
    Sep 28, 2014 at 22:30
  • want to neglect everything after the fourth field f10
    – Tak
    Sep 28, 2014 at 22:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .