LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Substring with specific condition (https://www.linuxquestions.org/questions/linux-newbie-8/substring-with-specific-condition-930456/)

VinRoh 02-21-2012 03:55 AM

Substring with specific condition
 
hi ,

I am trying to substring a line which is got while reading property file using shell scripting.
The line is something like this:
file\:/aaa/ccc/dd.jar, \^M

I am trying to get the substring as /aaa/ccc/dd.jar

Tried using awk for the same but not getting the right command.

Thanks

catkin 02-21-2012 04:55 AM

Assuming you want the string between : and , then:
Code:

awk -F '(:)|(,)' '{ print $2 }' input.txt

grail 02-21-2012 05:44 AM

Doesn't have to be quite so flash :)
Code:

awk -F"[:,]" '{print $2}' file

catkin 02-21-2012 05:55 AM

Quote:

Originally Posted by grail (Post 4608085)
Doesn't have to be quite so flash :)
Code:

awk -F"[:,]" '{print $2}' file

Ah, grail, I love your elegant minimalism and fluency :)

A point of style, though -- I would use single quotes for bash wherever double quotes are not necessary.

VinRoh 02-21-2012 09:55 PM

Hey thanks for your replies!!

Just for anyones interest ,I tried another way of doing it :

cut -d: -f2 | cut -d, -f1

David the H. 02-22-2012 09:21 AM

If you can get the string into a bash variable, there are quite a few options available.

Use parameter substitution:

Code:

string='file\:/aaa/ccc/dd.jar, \^M'
substring=${string#*:}
substring=${substring%,*}
echo "$substring"

Use bash's regex ability inside [[..]], and the resulting BASH_REMATCH array:

Code:

string='file\:/aaa/ccc/dd.jar, \^M'
re=':(.+),'
[[ $string =~ $re ]] && echo "${BASH_REMATCH[1]}"

Use IFS to set the field delimiters, and break it up with an array, or read.

Code:

string='file\:/aaa/ccc/dd.jar, \^M'
IFS=':,'
array=( $string )
echo "${array[1]}"
unset IFS

Code:

string='file\:/aaa/ccc/dd.jar, \^M'
IFS=':,' read -r _ substring _ <<<"$string"
echo "$substring"

More on bash string manipulation here.


Quote:

Originally Posted by catkin (Post 4608089)
A point of style, though -- I would use single quotes for bash wherever double quotes are not necessary.

I would generally agree with this, but the Japanese keyboard has the single-quote mark on the "7" key, and are not all that convenient to type, so it's personally easier for me to use double-quotes (on the "2" key, slightly easier to reach) most of the time.


All times are GMT -5. The time now is 06:48 PM.