How to manipulate a string, variable in shell
Hei everyone!
I have this variable in shell containing paths separated by a space:
LINE="/path/to/manipulate1 /path/to/manipulate2"
I want to add additional path string in the beginning of the string and as well right after the space so that the variable will have the result something like this:
LINE="/additional/path1/to/path开发者_如何学JAVA/to/manipulate1 /additional/path2/to/path/to/manipulate2"
I tried this one but only get the old paths
#!/bin/bash
LINE="/path/to/one /path/to/two"
NEW_PATH=`echo $LINE | sed "s/^\([^ ]\+\) \([^ ]\+\)/\/add1\1 \/add2\2/"`
echo "$NEW_PATH"
Any help appreciated Thanks in advance
This of courses messes with any previous arguments you might need to keep.
set $LINE
LINE="/additional/path1$1 /additional/path2$2"
Tested in bash/dash/ksh.
Edit: If keeping the original arguments is needed, this might be useful:
orig=$@
<stuff from above>
set $orig
firstPath=$(echo $LINE | cut -d' ' -f1)
secondPath=$(echo $LINE | cut -d' ' -f2)
firstPath="/additional/path1/to$firstPath"
secondPath="/additional/path2/to$secondPath"
$ test="/sbin /usr/sbin /bin /usr/bin /usr/local/bin /usr/X11R6/bin"
$ test2=$(for i in $test; do echo "/newroot${i}"; done)
$ echo $test2
/newroot/sbin /newroot/usr/sbin /newroot/bin /newroot/usr/bin /newroot/usr/local/bin /newroot/usr/X11R6/bin
Since you're using Bash:
If the additions are the same for each part:
LINE="/path/to/manipulate1 /path/to/manipulate2"
array=($LINE)
LINE=${array[@]/#//additional/path/to/}
If they are different:
LINE="/path/to/manipulate1 /path/to/manipulate2"
array=($LINE)
array[0]=/additional/path1/to${array[0]}
array[1]=/additional/path2/to${array[1]}
LINE=${array[@]}
Or, more flexibly:
LINE="/path/to/manipulate1 /path/to/manipulate2"
array=($LINE)
parts=(/additional/path1/to /additional/path2/to)
if (( ${#array[@]} == ${#parts[@]} ))
then
for ((i=0; i<${#array[@]}; i++))
do
array[i]=${parts[i]}${array[i]}
done
fi
LINE=${array[@]}
NEW_PATH=`echo $LINE | sed "s/^\([^ ]\+\) \([^ ]\+\)/\/add1\1 \/add2\2/"`
results in NEW_PATH =
/add1/path/to/manipulate1 /add2/path/to/manipulate2
精彩评论