How to add a string with spaces at the end of command output

6,105

Solution 1

STRING_WITH_SPACES="a string with spaces"
ls -l | sed "s/$/ $STRING_WITH_SPACES/"

Solution 2

Please don't parse the output of ls. There is no reason to and it complicates things. A safer way to write your script would be

#!/bin/sh
STRING_WITH_SPACES="this should be at the end of output"
find . -maxdepth 1 -mindepth 1 -ls | sed "s/$/ $STRING_WITH_SPACES/"
Share:
6,105

Related videos on Youtube

Babken Vardanyan
Author by

Babken Vardanyan

My blog: https://lazydevelo.com/

Updated on September 18, 2022

Comments

  • Babken Vardanyan
    Babken Vardanyan over 1 year

    I want to add a string with spaces at the end of each line of the output of ls command.

    #!/bin/sh
    STRING_WITH_SPACES="this should be at the end of output"
    ls -lh | sed 's|$| '$STRING_WITH_SPACES'|'
    

    The script above works fine when $STRING_WITH_SPACES has no spaces:

    -rw-r--r-- 1 me users 0 May  4 14:55 testfile thisshouldbeattheend
    

    However when there are spaces in $STRING_WITH_SPACES sed complains:

    sed: -e expression #1, char 9: unterminated `s' command
    

    How do I solve this?

  • fazie
    fazie about 10 years
    Please, don't get paranoid. Nobody parse output of ls here, but add some info of each line. Don't use ls at all, it's evil :-D
  • Babken Vardanyan
    Babken Vardanyan about 10 years
    My example was a minimal test case. My initial intention was to print contents of several directories which were specfied in a file, but only print filename, filesize and location(which was the STRING_WITH_SPACES).
  • terdon
    terdon about 10 years
    @fazie I know, which is why I upvoted your answer. I just thought the warning was worth mentioning since there are many problems with parsing ls.