How do I split a String in CSH?
Asked Answered
L

3

12

For example, I want to split "one,two,three" with comma as delimiter and use a loop to process the resulted three substring separately.

Leatri answered 12/10, 2011 at 4:8 Comment(0)
P
9

For example:

set s = "one,two,three"
set words = `echo $s:q | sed 's/,/ /g'`
foreach word ($words:q)
    echo $word:q
end

But consider whether csh is the right tool for whatever job you're doing:

http://www.bmsc.washington.edu/people/merritt/text/cshbad.txt

Peccary answered 12/10, 2011 at 4:21 Comment(2)
Thanks. What does :q mean here?Leatri
It quotes the variable; $s:q is similar to "$s". It's not needed for this example, but it might be in other cases (say, where you have whitespace in the data).Peccary
D
14

A simpler solution than the current one presented involves using the built-in substitution modifer -- there is no need or reason to wastefully use a loop or external command substitution in this instance:

set list = one,two,three
set split = ($list:as/,/ /)

echo $split[2] # returns two

() creates a list, the :s is the substitution modifier and :as repeats the subtitution as many times as needed.

Furthermore, t/csh does not require quoting of bare strings, nor variables that do not require forced evaluation.

Deeply answered 2/3, 2014 at 2:37 Comment(2)
What if list = "one,two or three,four"? How do you get: "two or three"?Precautionary
Maybe then: echo "$list" | awk -F',' '{print $2}' is better...Precautionary
P
9

For example:

set s = "one,two,three"
set words = `echo $s:q | sed 's/,/ /g'`
foreach word ($words:q)
    echo $word:q
end

But consider whether csh is the right tool for whatever job you're doing:

http://www.bmsc.washington.edu/people/merritt/text/cshbad.txt

Peccary answered 12/10, 2011 at 4:21 Comment(2)
Thanks. What does :q mean here?Leatri
It quotes the variable; $s:q is similar to "$s". It's not needed for this example, but it might be in other cases (say, where you have whitespace in the data).Peccary
H
3
set list = one,two,three
foreach i ( $list:as/,/ / )
  echo $i
end
Hellbent answered 18/8, 2015 at 22:55 Comment(1)
Can you explain wt is functionSmother

© 2022 - 2024 — McMap. All rights reserved.