Command substitution with string substitution

后端 未结 3 1894
挽巷
挽巷 2020-12-11 02:10

Is it possible to do something along the lines of:

echo ${$(ls)/foo/bar}

I\'m pretty sure i saw somewhere working example of something like

相关标签:
3条回答
  • 2020-12-11 03:01

    Why not just

    root@localhost:~# echo `pwd`_whatever_suffix
    /root_whatever_suffix
    
    0 讨论(0)
  • 2020-12-11 03:09

    Syntax ${...} only allows referencing a variable (or positional parameter), optionally combined with parameter expansion.

    Syntax $(...) (or, less preferably, its old-style equivalent, `...`), performs command substitution, which allows embedding arbitrary commands to whose stdout output the expression expands.

    Thus, you could combine the two features as follows:

    echo "$(lsOutput=$(ls); echo "${lsOutput//foo/bar}")"
    

    Note the uncomplicated nested use of $(...), which is one of the main advantages over `...`, whose use would require escaping here.

    That said, any variables you define inside the command substitution are confined to the subshell that the command runs in anyway, so you could make do with just a command that produces the desired output, given that it is only the stdout output that matters.

    echo "$(ls | sed 's/foo/bar/')"
    
    0 讨论(0)
  • 2020-12-11 03:13

    You can use pipe | with sed, example:

    $ echo ABC | sed 's/B/_/'
    A_C
    

    Or variable substitution, all explained here, and especially at "Variable expansion / Substring replacement" section, and below an example from me:

    $ var=ABC
    $ echo ${var//B/_}
    A_C
    
    0 讨论(0)
提交回复
热议问题