This is really self explanatory. I’m working in a bash shell and I’m really new to shell scripting. I’ve found a lot of information about using tr and sed but all the examples I have found so far are removing delimiters and new lines. I really want to do the opposite of that. I want to be able to separate based on a blank space. I have a string like “abcd efgh” and I need it to be “abcd” “efgh” (all without quotes, just to show groupings).
I’m sure this is much simpler than I’m making it, but I’m very confused.
Updated Question:
I have a column of PIDs that I have put into an array, but each element of the array has both the pids in the column.
Column:
1234
5678
when I print out the entire array, all the different columns have been added so I have all the values, but when I print out a single element of my array I get something like:
1234 5678
which is not what I want.
I need to have an element for 1234 and a separate one for 5678.
This is my code so far:
!/bin/bash
echo "Enter the File Name"
read ips
index=0
IFS=' '
while read myaddr myname; do
myips[$index]="$myaddr"
names[$index]="$myname"
index=$(($index+1))
done < $ips
echo "my IPs are: ${myips[*]}"
echo "the corresponding names are: ${names[*]}"
echo "Total IPs in the file: ${index}"
ind=0
for i in "$myips[@]}"
do
echo $i
pids=( $(jps | awk '{print $1}') )
for pid in "${pids[@]}"; do
echo $pid
done
echo "my PIDs are: ${pids}"
for j in "${pids[@]}"
do
mypids[$ind]="$j"
ind=$(($ind+1))
done
done
echo "${mypids[*]}"
echo "The 3rd PID is: ${mypids[2]}"
SAMPLE OUTPUT:
Total IPs in the file: 6
xxx.xxx.xxx.xxx
5504
1268
1
xxx.xxx.xxx.xxx
5504
4352
1
xxx.xxx.xxx.xxx
5504
4340
1
5504
1268 5504
4352 5504
4340
The 3rd pid is: 5504
4340
I need each pid to be separate, so that each element of the array, is a single pid. So for instance, the line “The 3rd pid is: ” needs to look something like
The 3rd pid is: 5504
and the 4th element would be 4340
Try
cut:Alternatively, if at some point you want to do something more complex, do look into
awkas well:To address your updated question:
If you want to load a column of data into an array, you could do something like this:
To address the example code you posted, the reason for your problem is that you’ve change
$IFSto a space (IFS=' ') which means that your columns which are separated by newlines are no longer being split.Consider this example:
To avoid this problem, a common approach is to always backup the original
IFSand replace it once you’ve done using the updated value. E.g.