softghost
softghost

Reputation: 1197

How can I split a string in shell?

I have two strings and I want to split with space and use them two by two:

namespaces="Calc Fs"
files="calc.hpp fs.hpp"

for example, I want to use like this: command -q namespace[i] -l files[j]

I'm a noob in Bourne Shell.

Upvotes: 0

Views: 373

Answers (5)

Sebastian Stumpf
Sebastian Stumpf

Reputation: 2791

If you are using zsh this could be very easy:

files="calc.hpp fs.hpp"

# all elements
print -l ${(s/ /)files}

# just the first one
echo ${${(s/ /)files}[1]} # just the first one

Upvotes: 1

jfg956
jfg956

Reputation: 16768

I wanted to find a way to do it without arrays, here it is:

paste -d " " <(tr " " "\n" <<< $namespaces) <(tr " " "\n" <<< $files) |
  while read namespace file; do
    command -q $namespace -l $file
  done

Two special usage here: process substitution (<(...)) and here strings (<<<). Here strings are a shortcut for echo $namespaces | tr " " "\n". Process substitution is a shortcut for fifo creation, it allows paste to be run using the output of commands instead of files.

Upvotes: 1

Gordon Bailey
Gordon Bailey

Reputation: 3921

if what you want to do is loop through combinations of the two split strings, then you want something like this:

for namespace in $namespaces
do
   for file in $files
   do
      command -q $namespace -l $file
   done
done

EDIT: or to expand on the awk solution that was posted, you could also just do:

 echo $foo | awk '{print $'$i'}'

EDIT 2:

Disclaimer: I don not profess to be any kind of expert in awk at all, so there may be small errors in this explanation.

Basically what the snippet above does is pipe the contents of $foo into the standard input of awk. Awk reads from it's standard in line by line, separating each line into fields based on a field separator, which is any number of spaces by default. Awk executes the program that it is given as an argument. In this case, the shell expands '{ print $'$1' }' into { print $1 } which simply tells awk to print field number 1 of each line of its input.

If you want to learn more I think that this blog post does a pretty good job of describing the basics (as well as the basics of sed and grep) if you skip past the more theoretical stuff at the start (unless you're into that kind of thing).

Upvotes: 1

j_mcnally
j_mcnally

Reputation: 6968

echo "hello world" | awk '{split($0, array, " ")} END{print array[2]}'

is how you would split a simple string.

Upvotes: 2

SiegeX
SiegeX

Reputation: 140557

Put them into an array like so:

#!/bin/bash

namespaces="Calc Fs"
files="calc.hpp fs.hpp"
i=1
j=0

name_arr=( $namespaces )
file_arr=( $files )

command -q "${name_arr[i]}" -l "${file_arr[j]}"

Upvotes: 3

Related Questions