Search code examples
bashbash4

If It is a directory append text


Im trying to append a text if it is a directory.

calculation="$(ls -l | sed 's/[d]/This is a directory -> /')"

printf "%s" "${calculation}"

Im just womdering if somebody could give me a tip on what is wrong with my code


Solution

  • Not sure what you're doing, but:

    $ calculation="$(ls -l | sed 's/^[d]/This is a directory -> d/')"
    

    Two changes:

    • I added a ^ which says that the line must begin with one of the characters in the square brackets (which d is the only one).
    • I added a d on the end of the substitution, since you replaced it with your string. This way, your directories still have the correct permissions.

    You don't need [d]. Just d would do:

    $ calculation="$(ls -l | sed 's/^d/This is a directory -> d/')"
    

    And you don't need ${calculation}:

    $ echo "$calculation"
    

    or, if you want to use printf:

    $ printf "%s\n" "$calculation"   # Note the ending NL which printf doesn't supply
    

    Or even more simply:

    $ printf "$calculation\n"