Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut a string after a specific character in unix

So I have this string:

[email protected]:/home/some/directory/file

I just want to extract the directory address meaning I only want the bit after the ":" character and get:

/home/some/directory/file

thanks.

I need a generic command so the cut command wont work as the $var variable doesn't have a fixed length.

like image 755
canecse Avatar asked Aug 23 '13 07:08

canecse


People also ask

How do I cut out a specific character in Unix?

To cut by character use the -c option. This selects the characters given to the -c option. This can be a list of comma separated numbers, a range of numbers or a single number. Where your input stream is character based -c can be a better option than selecting by bytes as often characters are more than one byte.

How do I cut a string after a specific character in Bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed.

How do you cut a string in Unix?

The cut command in UNIX is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text.

How do I strip a string in Linux?

`sed` command is another option to remove leading and trailing space or character from the string data. The following commands will remove the spaces from the variable, $myVar using `sed` command. Use sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command.


4 Answers

Using sed:

$ [email protected]:/home/some/directory/file
$ echo $var | sed 's/.*://'
/home/some/directory/file
like image 110
falsetru Avatar answered Oct 22 '22 04:10

falsetru


This might work for you:

echo ${var#*:}

See Example 10-10. Pattern matching in parameter substitution

like image 29
potong Avatar answered Oct 22 '22 04:10

potong


This will also do.

echo $var | cut -f2 -d":"
like image 19
Manish V Avatar answered Oct 22 '22 06:10

Manish V


For completeness, using cut

cut -d : -f 2 <<< $var

And using only bash:

IFS=: read a b <<< $var ; echo $b
like image 11
chthonicdaemon Avatar answered Oct 22 '22 04:10

chthonicdaemon