Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 7 down vote accepted
STRING_WITH_SPACES="a string with spaces"
ls -l | sed "s/$/ $STRING_WITH_SPACES/"
share|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

#!/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|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 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). –  user2529583 May 4 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 at 17:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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