Home > OS >  how to apply sed command on a array variable
how to apply sed command on a array variable

Time:12-02

The primary goal is to know how to use the sed command on a array-variable rather then a file.

Secondary is to remove the path out of the array, the final output should contain only the files names

sample data:

path=$(pwd) 
echo $path
>> /home/peter/my_commands

array=($path/*.sh)
echo "${array[@]}"
>> /home/peter/my_commands/func1.sh /home/peter/my_commands/main.sh /home/peter/my_commands/test.sh

desired output: func1.sh main.sh test.sh this values inside of array-variable called array2

summarizing:

#input data
array=(/home/peter/my_commands/func1.sh /home/peter/my_commands/main.sh /home/peter/my_commands/test.sh)

#sed command to make the transformation
#HERE..

#output will be
array2=(func1.sh  main.sh  test.sh)

failed attempts:

# sed -i -e 's.$path..'
# array2=$(sed -n '2p' $path)
# array2=(($path/*.sh) | sed -i "s.$path..")
# array2="$(echo $array | sed -i -e "s.$path..g")"
# array2=$(sed -i -e "s./.." <<< "$array")

echo "${array2[@]}"

CodePudding user response:

Like this:

$ array=(/home/peter/my_commands/func1.sh /home/peter/my_commands/main.sh /home/peter/my_commands/test.sh)
$ array2=( "${array[@]##*/}" )
$ printf '%s\n' "${array2[@]}"
func1.sh
main.sh
test.sh

Using bash parameter expansion

  • Related