How to split the contents of `$ PATH` into separate lines?

Suppose it echo $PATHgives /first/dir:/second/dir:/third/dir.

Question: How to echo the contents of $PATHone directory at a time, as in:

```
$ newcommand $PATH
/first/dir
/second/dir
/third/dir
```

Preferably, I'm trying to figure out how to do this with a loop forthat returns a single instance echofor a directory instance in $PATH.

+4
source share
6 answers
echo "$PATH" | tr ':' '\n'

Gotta do the trick. This will simply print the result echo "$PATH"and replace any colon with a newline separator.

, $PATH $PATH, .

+5

:

echo "$PATH" | sed -e 's/:/\n/g'

(. sed s; sed -e 'y/:/\n/' tr ":" "\n" . )

, : for . , Unix Philosophy:

Unix: , . . , .

:

echo "$PATH" | sed -e 's/:/\n/g' | xargs -n 1 echo

PATH, echo . -n 1 xargs 1 ; , echo "$PATH" | sed -e 'y/:/ /'.
xargs, - , , :

echo -n "$PATH" | xargs -d ':' -n 1

-d ':' xargs : , , -n /bin/echo , .

+2

- echo awk.

echo $PATH | awk 'BEGIN {FS=":"} {for (i=0; i<=NF; i++) print $i}'

, .

echo "$PATH" | awk 'BEGIN {FS=":"; OFS="\n"} {$1=$1; print $0}'
+1

( - ), IFS read -a:

IFS=: read -r -a patharr <<<"$PATH"
printf %s\\n "${patharr[@]}"

, for:

for dir in "${patharr[@]}"; do
    echo "$dir"
done
+1

tr (), (:) (\n), for.

directories=$(echo $PATH | tr ":" "\n")
for directory in $directories
do
    echo $directory
done
0

, PATH , :

for dir in ${PATH//:/ }; do
    echo $dir
done

If there are embedded spaces, this will fail.

0
source

Source: https://habr.com/ru/post/1614082/


All Articles