Reputation: 91
Playing with sed - the commands below do what's required but one liners would be better. I have tried combining the first two commands (with a separating ';') to remove the trailing ':' without success. Otherwise, resorted to removing the last ':' and writing to a new file to perform the next operation.
File 'sys' with a single line containing a variable number characters and ':' separator. For example;
Input - 'sys' first line 3.000000:50:
desired output, two variables thd=3 mem=50
thd=$(echo | sed 's/.......:.*//' < sys)
sed 's/:$//' < sys > sys1
mem=$(echo | sed 's|........:||' < sys1)
Is there a way to combine the first two sed commands to avoid writing a second file? I have tried this various ways
Something like this - EDIT: this is the wrong order to remove the trailing ':'
thd=$(echo | sed 's/:$//;s/.......:.*//' < sys)
mem=$(echo | sed 's|........:||' < sys1)
Output 3 50:
with the separator attached.
EDIT: This is the correct order and produces the desired output. Bash does not save the result of the first operation in the file sys. Which I should have picked up in the 3 liner.
thd=$(echo | sed 's/.......:.*//' < sys)
mem=$(echo | sed 's|........:||;s/:$//' < sys)
Upvotes: 0
Views: 951
Reputation: 23826
Try this:
$ echo '3.000000:50:' | { IFS='.:' read thd x mem; echo "'$thd' '$mem'"; }
'3' '50'
Or this:
$ sys='3.000000:50:'; IFS='.:' read thd x mem <<< "$sys"; echo "'$thd' '$mem'"
'3' '50'
The above sets the "dont care" variable x
. If you do not like that, you can assign mem
twice.
$ sys='3.000000:50:'; IFS='.:' read thd mem mem <<< "$sys"; echo "'$thd' '$mem'"
'3' '50'
Upvotes: 1
Reputation: 5762
If you need two variables to be assigned values independently, the first containing the number before the point and the second the number between the colons, you can use an approach like
thd=$(cut -f1 -d. < sys)
mem=$(cut -f2 -d: < sys)
Assigning both at the same time is also possible:
read thd mem < <(tr "." ":" < sys | cut -f1,3 -d: --output-delimiter=" ")
Upvotes: 1