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

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?

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

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

STRING_WITH_SPACES="this should be at the end of output"
find . -maxdepth 1 -mindepth 1 -ls | sed "s/$/ $STRING_WITH_SPACES/"
| improve this answer | |
  • 1
    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 – fazie May 4 '14 at 15:32
  • 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). – Babken Vardanyan May 4 '14 at 15:51
  • @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. – terdon May 4 '14 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.