How can I split following input into stwo strings:
Input:
1^~^2^~^3^~^4^~^5^~^6^~^7^~^8^~^9
Output:
$string1 = 1^~^2^~^
$string2 = 3^~^4^~^5^~^6^~^7^~^8^~^9
Note: the length of string may vary, say upto 15. String 1 will contain only first two. string2 will contain rest.
pamu
October 8, 2012, 1:58am
2
on which pattern you want to split..?
$ sed 's/3/\n&/' file
1^~^2^~^
3^~^4^~^5^~^6^~^7^~^8^~^9
$ sed 's/\^~\^/&\n/2' file
1^~^2^~^
3^~^4^~^5^~^6^~^7^~^8^~^9
$sed 's/[0-9]/\n&/3' file
1^~^2^~^
3^~^4^~^5^~^6^~^7^~^8^~^9
I want the code in perl and want to split the string and store in two variables as I said above.
The separator will be '^~^'
Please refer to my first post.
#!/usr/bin/perl -w
use strict;
my $var='1^~^2^~^3^~^4^~^5^~^6^~^7^~^8^~^9';
my ($string1,$string2);
if ($var =~ /^((?:[0-9]+\^~\^){2})(.*)/) {
$string1 = $1;
$string2 = $2;
}
if (defined $string1 and defined $string2) {
print "String1 is : $string1\n";
print "String2 is : $string2\n";
}
producing
String1 is : 1^~^2^~^
String2 is : 3^~^4^~^5^~^6^~^7^~^8^~^9
pamu
October 8, 2012, 2:18am
5
som.nitk:
I want the code in perl
Please check your thread title. You have mentioned there in sed, perl.
If you want in perl only use elixir's solution.
Why does it not match any alphanumeric characters with following?
if ($var =~ /^((?:[a-zA-Z0-9]*\^~\^){2})(.*)/) {
$string1 = $1;
$string2 = $2;
}
# Bash script
#!/bin/bash
string='1^~^2^~^3^~^4^~^5^~^6^~^7^~^8^~^9'
# splitting point
var1=3
string1=`echo "$string" | awk -F["$var1"] '{print $1}'`
string2=`echo "$string" | awk -F["$var1"] -v var1="$var1" '{print var1$2}'`
echo "Original String : $string"
echo "After splitting: "
echo "String1 is : $string1"
echo "String2 is : $string2"
# Usage
./strings.sh
# Result
Original String : 1^~^2^~^3^~^4^~^5^~^6^~^7^~^8^~^9
After splitting:
String1 is : 1^~^2^~^
String2 is : 3^~^4^~^5^~^6^~^7^~^8^~^9
What exactly do you mean by this? Please elaborate by mentioning what is not matching.
If it contains alphanumeric with space like:
1^~^GH^~^23 Banergatta^~^Bangalore 560001^~^India^~^MISS B DAS^~^
If the data will be containing spaces, don't you think that you should also provide for spaces in the regexp?
if ($var =~ /^((?:[a-zA-Z0-9 ]+\^~\^){2})(.*)/) {
$string1 = $1;
$string2 = $2;
}