Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append strings to other strings in a data set?

I want to append several strings in a data set with custom strings.

Example

Content of Dataset:

Test1
Test2
Test3

Result after appending:

Test1.com
Test2.com
Test3.com

Would I have to use regex to parse to the end of each Test[n] to be able to append it with a custom string (.com)? Has anyone got an example that describes exactly how to do it?

I am reading from a SQL-Table and writing values into a DataSet which is exported to CSV the following way:

$DataSet.Tables[0] | ConvertTO-Csv -Delimiter ',' -NotypeInformation |`% { $_ -replace '"','' } |  out-file  $outfile -Encoding "unicode"

The DataSet contains of Strings such as:

Banana01
Banana02
Apple01
Cherry01
Cherry02
Cherry03

The thing I want to do is append .com to only Cherry01, Cherry02, and Cherry03, and after appending .com, export it as a CSV file.

like image 816
t1red Avatar asked Jul 25 '12 11:07

t1red


People also ask

How do you append a string to another string in Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.

How do you append a string to another in Python?

Method 1: Concatenate Strings Into a String using the += operator. This operator can be used to perform this particular task of concatenating the string. This is quite simpler than the traditional methods that are employed in other languages, like using a dedicated function to perform this particular task.

Which function is used to append one string into another string?

The strcat function is used to concatenate one string (source) at the end of another string (destination).


2 Answers

There are many ways. Here are a few:

# Using string concatenation
'Test1','Test2','Test3' | Foreach-Object{ $_ + '.com' }

# Using string expansion
'Test1','Test2','Test3' | Foreach-Object{ "$_.com" }

# Using string format
'Test1','Test2','Test3' | Foreach-Object{ "{0}{1}" -f $_,'.com' }
like image 60
Shay Levy Avatar answered Oct 04 '22 16:10

Shay Levy


You could use something like this:

Example 1

$t = "test"
$t = $t + ".com"

Example 2

$test = @("test1","test2")

$test | ForEach-Object {
$t = $_ + ".com"
Write-Host $t}

With your added code I did this. I don't have a database to test it on, so I made the data set manually, so you might just have to change the $DataSet[0] in my code to $DataSet.Tables[0].

$DataSet[0] | ConvertTO-Csv -Delimiter ',' -NotypeInformation  | Foreach-Object{$T=$_
IF($T -match "(Cherry\d\d)"){$T = $T -replace "(Cherry\d\d)(.+)",'$1.com$2'};$T } |  out-file  $outfile -Encoding "unicode"
like image 39
justinf Avatar answered Oct 04 '22 16:10

justinf